My code which was linked to openssl 0.98 had a AES decryption functionality which was working fine.
This is the code.
const int bits = 256;
AES_KEY key;
iRes = AES_set_decrypt_key((const unsigned char *)szSecretKey, bits, &key);
unsigned char szSigBytes[MAX_PATH] = "";
unsigned char *pSigBytes = szSigBytes;
unsigned char *pSignature = szSignature;
AES_decrypt(pSignature, pSigBytes, &key);
AES_decrypt(pSignature + 16, pSigBytes + 16, &key);
cout<<pSigBytes<<endl;
However, after migrating to openssl 1.0.1p, I had to use the EVP functions as the non EVP functions were failing in FIPS mode. So I modified the code to
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ciphertext_len = strlen((const char*)in);
if(!(ctx = EVP_CIPHER_CTX_new()));
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), NULL, SecretKey, NULL))
return;
if(1 != EVP_DecryptUpdate(ctx, out, &len, in, ciphertext_len))
return;
if(1 != EVP_DecryptUpdate(ctx, out + 16, &len, in + 16, ciphertext_len - len))
return;
EVP_DecryptFinal_ex(ctx, out + len, &len);
EVP_CIPHER_CTX_free(ctx);
The results are almost matching, but for some of the few last characters. Any idea, what am I doing wrong here?
Edit: I see that the second 16 bytes are not getting decrypted while using EVP_DecryptUpdate.
I have extracted the second 16 bytes into an array and tried to decrypt it. I see that it goes successfully when I use AES_decrypt, but returns "" when I use EVP_DecryptUpdate. The cipher length is only 2 bytes. Can this be a reason why the decryption is failing?
See the modified code below.
unsigned char temp[MAX_PATH] = "BoQ=\n";
unsigned char result[MAX_PATH] = "";
unsigned char data[MAX_PATH] = "";
Decode(temp, data);
//Decrypting with AES_Decrypt
AES_KEY key;
unsigned char DecodedSecretKey[MAX_PATH];
ZeroMemory(DecodedSecretKey, MAX_PATH);
Decode(secretKey, DecodedSecretKey);
AES_set_decrypt_key((const unsigned char *)DecodedSecretKey, 256, &key);
AES_decrypt(data, result, &key);//result returns the proper result
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Decrypting with EVP_DecryptUpdate
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
int ciphertext_len = strlen((const char*)data);
if(!(ctx = EVP_CIPHER_CTX_new()));
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_ecb(), NULL, SecretKey, NULL))
return;
if(1 != EVP_DecryptUpdate(ctx, result, &len, data, ciphertext_len))
return;
EVP_DecryptFinal_ex(ctx, result + len, &len);
EVP_CIPHER_CTX_free(ctx);
//Here the array result is always empty
I just figured out the problem. It was really a very silly one.
int ciphertext_len = strlen((const char*)data);
I was deciding the length of an encrypted string, using strlen, which is wrong, and I just learned it the hard way.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments