sm3代码
#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
void handleErrors(void)
{
ERR_print_errors_fp(stderr);
abort();
}
void test_sm3()
{
unsigned char data[] = "Hello, SM3!";
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digest_len;
EVP_MD_CTX *mdctx;
mdctx = EVP_MD_CTX_new();
if (mdctx == NULL)
handleErrors();
if (EVP_DigestInit_ex(mdctx, EVP_sm3(), NULL) != 1)
handleErrors();
if (EVP_DigestUpdate(mdctx, data, sizeof(data) - 1) != 1)
handleErrors();
if (EVP_DigestFinal_ex(mdctx, digest, &digest_len) != 1)
handleErrors();
EVP_MD_CTX_free(mdctx);
printf("SM3 Digest: ");
for (unsigned int i = 0; i < digest_len; i++)
printf("%02x", digest[i]);
printf("\n");
}
sm4代码
GNU nano 4.8 sm4_test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
void handleErrors(void)
{
fprintf(stderr, "Error occurred\n");
exit(1);
}
void test_sm4(const unsigned char *key, const unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
unsigned char ciphertext[128];
int len;
// Create and initialize the context
ctx = EVP_CIPHER_CTX_new();
if (!ctx)
handleErrors();
// Encrypt the plaintext using SM4 in CBC mode
if (EVP_EncryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, NULL) != 1)
handleErrors();
if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, strlen((char *)plaintext)) != 1)
handleErrors();
if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1)
handleErrors();
EVP_CIPHER_CTX_free(ctx);
printf("SM4 Ciphertext: ");
for (int i = 0; i < len + strlen((char *)plaintext); i++)
printf("%02x", ciphertext[i]);
printf("\n");
}
[ 已读取 54 行 ]
^G 求助 ^O 写入 ^W 搜索 ^K 剪切文字 ^J 对齐 ^C 游标位置 M-U 撤销
^X 离开 ^R 读档 ^\ 替换 ^U 粘贴文字 ^T 拼写检查 ^_ 跳行 M-E 重做
标签:ctx,OpenSSL,len,unsigned,API,实验,EVP,include,handleErrors
From: https://www.cnblogs.com/lizhuotong/p/17776565.html