首页 > 解决方案 > 加密更新时出现 OpenSSL AES 分段错误

问题描述

我有设置大小的字符串并尝试对其进行 AES 加密,但我得到分段错误EVP_EncryptUpdate

size_t dec_len = 20;
char *dec = malloc(dec_len + 1);

//Fill dec
...
//Encrypt

EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
unsigned char *key = (unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, &key, NULL);
EVP_CIPHER_CTX_set_padding(ctx, 0);
unsigned char *ciphertext;
int ciphertext_len;
EVP_EncryptUpdate(ctx, ciphertext, &ciphertext_len, dec, dec_len);
EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &ciphertext_len);
EVP_CIPHER_CTX_free(ctx);

我不知道是什么原因造成的。谢谢你。

标签: cencryptionopensslaes

解决方案


根据OpenSSL 文档,声明为

int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
    ENGINE *impl, const unsigned char *key, const unsigned char *iv);

请注意,key声明为const unsigned char *key.

但是你的代码是

unsigned char *key = (unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, &key, NULL);

您将指针的地址传递给函数 -不是. 你想传递字符串的地址,它指向:keyunsigned char **const unsigned char *key

const unsigned char *key = (const unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, NULL);

推荐阅读