解密内存问题
我最近制作了一个使用 AES256 加密/解密数据的服务器,花了一段时间才能正确发送。但是现在我遇到了一个问题,我相信这是内存问题,如果我发送“hello”这个词,它会很好地解密,如果我然后发送“helloo”,它也会很好地解密,但如果我发送更短的内容比“helloo”之后,它在解密过程中会出错,如果你打印它收到的加密字符串,它会得到它应该有的内容加上旧字符串的额外长度。
例如
hello: ####################
helloo: ##############################
hi: #####(#########################) //has the additional length made up from the encrypted string of "helloo" minus the first however many characters "hi" is
代码:
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 byte *)iv, CryptoPP::AES::BLOCKSIZE);
CryptoPP::AuthenticatedDecryptionFilter adf(dec, new CryptoPP::StringSink(plaintext));
adf.Put((const byte *)decodedtext.data(), decodedtext.size());
adf.MessageEnd();
return plaintext;
}
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 byte *)iv, CryptoPP::AES::BLOCKSIZE);
CryptoPP::AuthenticatedDecryptionFilter adf(dec, new CryptoPP::StringSink(plaintext));
adf.Put((const byte *)decodedtext.data(), decodedtext.size());
adf.MessageEnd();
return plaintext;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 valgrind 来查找代码中的内存错误。
哦,还有一个提示:发布代码本身,它可能会带来更有趣的答案。
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