如何解决加密更新中的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);
我不知道是什么原因造成的。谢谢。
解决方法
每个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,key,NULL);
,
通过分配密文变量解决。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。