SM4測試

天问—九章發表於2024-04-29

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;

}``


相關文章