问题描述
我现在用的EVP库在这里找到:
I am using the EVP library found here: https://www.openssl.org/docs/manmaster/crypto/EVP_EncryptInit.html
下面是我的两个加密和解密功能:
Here are my two encryption and decryption functions:
我试图使用加密AES 128 CBC的字符串。
I am trying to encrypt a string using AES 128 CBC.
该字符串通常是格式字1字词2 WORD3
char* encrypt(char *s, char *key) {
unsigned char iv[16] = {[0 ... 15 ] = 0};
unsigned char outbuf[1024] = {[0 ... 1023] = 0};
int outlen1, outlen2;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if (EVP_EncryptUpdate(&ctx, outbuf, &outlen1, s, strlen(s)) == 1) {
if (EVP_EncryptFinal_ex(&ctx, outbuf + outlen1, &outlen2) == 1) {
EVP_CIPHER_CTX_cleanup(&ctx);
return strdup(outbuf);
}
}
EVP_CIPHER_CTX_cleanup(&ctx);
return NULL;
}
char* decrypt(char *s, char *key) {
unsigned char iv[16] = {[0 ... 15 ] = 0};
unsigned char outbuf[1024] = {[0 ... 1023] = 0};
int outlen1, outlen2;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if (EVP_DecryptUpdate(&ctx, outbuf, &outlen1, s, strlen(s)) == 1) {
printf("After decrypt update\n");
if (EVP_DecryptFinal_ex(&ctx, outbuf + outlen1, &outlen2) == 1) {
printf("After decrypt final\n");
EVP_CIPHER_CTX_cleanup(&ctx);
return strdup(outbuf);
}
}
EVP_CIPHER_CTX_cleanup(&ctx);
return NULL;
}
问题是解密最终函数可以使用一些字符串,但不能在其他人。
The problem is the decryption final function works on some strings but not on others.
如果它被加密之前的字符串是像猫狗牛
,解密工作。
If the string before it is encrypted is something like cat dog cow
, the decryption works.
但如果是像蝙蝠狗牛
,解密特别是在 EVP_DecryptFinal_ex()
功能失效。
But if it is like bat dog cow
, the decryption fails in particular at the EVP_DecryptFinal_ex()
function.
对于一些字符串,解密总是失败在 EVP_DecryptFinal_ex()
功能。它不会返回1。
For some strings, the decryption always fails at the EVP_DecryptFinal_ex()
function. It does not return 1.
任何想法,问题可能是什么?填充可能?我刚才似乎无法推测出来。
Any idea what the problem could be? Padding maybe? I just can't seem to figure it out.
推荐答案
您可能错过加密的字符串可以包含零字节,所以在DecryptUpdate strlen的(S)具有过低值。你有来自加密记住加密的数据是多长,并使用该值用于解密
You probably miss that the encrypted string may contain zero-bytes, so the strlen(s) in DecryptUpdate has a too low value. You have to remember from encrypt how long the encrypted data is and use that value for decrypting.
这篇关于采用AES-128 / CBC时EVP_DecryptFinal_ex间歇性故障解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!