I've recently been making a server which uses AES256 to encrypt/decrypt data, it took awhile to get it to send correctly. However now I'm having an issue I believe is down to memory, if I send the word "hello" it'll decrypt fine, if I then send "helloo", it'll also decrypt fine, but if I send anything shorter than "helloo" after, it'll error during decryption and if you print the encrypted string it received it's got what it should have plus the additional length of the old string.
e.g
hello: ####################
helloo: ##############################
hi: #####(#########################) //has the additional length made up from the encrypted string of "helloo" minus the first however many characters "hi" is
The code:
std::string decryptString(std::string ciphertext, byte *key, byte *iv)
{
std::string decodedtext;
CryptoPP::StringSource(ciphertext, true,
new CryptoPP::HexDecoder(new CryptoPP::StringSink(decodedtext)));
std::string plaintext;
CryptoPP::GCM<CryptoPP::AES>::Decryption dec;
dec.SetKeyWithIV((const byte *)key, CryptoPP::AES::MAX_KEYLENGTH,
(const byt开发者_如何学JAVAe *)iv, CryptoPP::AES::BLOCKSIZE);
CryptoPP::AuthenticatedDecryptionFilter adf(dec, new CryptoPP::StringSink(plaintext));
adf.Put((const byte *)decodedtext.data(), decodedtext.size());
adf.MessageEnd();
return plaintext;
}
Try using valgrind to find memory errors in your code.
Oh, and a tip: post the code itself, it might lead to more interesting answers.
If you always pass the same initialization vector to this method, may be the reason is in it. Try
dec.Resynchronize(iv);
精彩评论