SM4测试

SM4代码如下:

 

``#include <openssl/evp.h>

include <stdio.h>

include <string.h>

int main() {
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;

unsigned char *plaintext = (unsigned char *)"20211122";
unsigned char key[] = "2021112220211122"; // SM4 key
unsigned char iv[] = {0};  // 初始化向量全零,实际应用中应随机生成

unsigned char ciphertext[128];
unsigned char decryptedtext[128];

// 初始化加密操作的 context
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv);

// 加密消息,这里plaintext的长度需要≤ 128
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, strlen((char *)plaintext));
ciphertext_len = len;

// 结束加密操作,处理任何剩余的加密字节
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
ciphertext_len += len;

// 去初始化 context
EVP_CIPHER_CTX_free(ctx);

printf("Ciphertext is:\n");
for (int i = 0; i < ciphertext_len; i++) {
    printf("%02x", ciphertext[i]);
}
printf("\n");

// 解密操作
ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv);

EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len);
int plaintext_len = len;

// 结束解密操作,处理任何剩余的加密字节
EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len);
plaintext_len += len;

// 添加字符串结束符
decryptedtext[plaintext_len] = '\0';

// 去初始化 context
EVP_CIPHER_CTX_free(ctx);

printf("Decrypted text is:\n%s\n", decryptedtext);

return 0;

}``


posted @ 2024-04-29 09:15  天问—九章  阅读(58)  评论(0编辑  收藏  举报