加密更新时 OpenSSL AES 分段错误

OpenSSL AES Segmentation Fault on Encrypt Update

我有设置大小的字符串并尝试对其进行 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);

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

根据 the OpenSSL documentation,声明为

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);

您正在将 key 指针的 地址 传递给函数 - unsigned char ** 而不是一个const unsigned char *。你要传递字符串的地址,就是key指向的:

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

通过分配密文变量解决