All,
I'm trying to encrypt a string in Java using AES 256 and decrypt it in C++ using openssl. In java I:
- Generated a SecretKey in a JCEKS
- Encrypted the string
- encoded both the string and getEncoded() from the SecretKey in base64
Now I'm trying to decrypt it in C++ using OpenSSL:
string encoded = string("LtANvfmnb5zj+4+g6I7hC53eHMIRa4BOkzMpXYLlA9DRnRWjQjO9uMot6hR7zzTIOtdmkRJ16aVZRfIT3sYn17jYEJjvAN9/N7FbblLplCtOuHatGffH0pSf8lu76SUzDIZU+EXgTnK1SsEa4sndcXvg5jaElxr4GCHq+F2aL7t+LVjbqWg4kpYkYbKdrKQgOsMCbBBG2aMFTmQ/cxnVyH8juC/ZTSrPMyjZ7KxS0P9PzfmxkeSi3VsBIjXL6Q4pneZeemP+1JdG02yQWhruJUuH5aRE0piQ776lxt6g0wU=");
string encodedKey = string("1rE2AM4Xf0ItxN/s1oDvaNmXhXlVF3hE+vSkyMPzDl4=");
string decodedEnc = base64_decode(encoded);
string decodedKey = base64_decode(encodedKey);
const unsigned char *keyBytes = reinterpret_cast<开发者_开发问答const unsigned char*>(decodedKey.c_str());
const unsigned char *in = reinterpret_cast<const unsigned char*>(decodedEnc.c_str());
cout << "initializing" << endl;
AES_KEY key;
/* set the encryption key */
AES_set_encrypt_key(keyBytes, 256, &key);
unsigned char *out = (unsigned char*) malloc(1024);
cout << "Decrypting" << endl;
AES_ecb_encrypt(in,out,&key,AES_DECRYPT);
cout << "decrypted " << out << endl;
char* dec = reinterpret_cast< char*>(out);
string decrypted = std::string(dec);
cout << "Decrypted String : '" << decrypted << "'" << endl;
All I am getting is garbage printed to the terminal. I feel like I'm close, so any help would be greatly appreciated.
Thanks Marc
according to my understanding, try the decryption key and then AES_decrypt
which should be called as follows:
cout << "Decrypting" << endl;
from this line onwards... use the code as follows:
AES_KEY k
AES_set_decrypt_key(keyBytes, 256, &k);
unsigned char* outdecrypt = new unsigned char[1024];
AES_decrypt(out, outdecrypt, &k);
In addition to checking key length, make sure both Java and C/OpenSSL are using the same Initialization Vector (IV). Some frameworks initialize it for you, others do not. This is the vector of data that the initial block will be XOR'd with (IIRC, at least in one encoding mode), where AES XORs each block against the previous block. Without this (IIRC it's CBC / cyclic block coding), the last block can be inspected as it typically has padding that is easy to verify in a brute force manner.
I believe one of the Java framework or OpenSSL supports 128 bit keys, and not 256 byte keys.
<Referenced bug report>
精彩评论