我有一段代码加密和解密消息。
QString AesUtils::encrypt(QString message, QString aesKey)
{
string plain = message.toStdString();
qDebug() << "Encrypt" << plain.data() << " " << plain.size();
string ciphertext;
// Hex decode symmetric key:
HexDecoder decoder;
string stdAesKey = aesKey.toStdString();
decoder.Put((byte*)stdAesKey.data(), aesKey.size());
decoder.MessageEnd();
word64 size = decoder.MaxRetrievable();
char *decodedKey = new char[size];
decoder.Get((byte *)decodedKey, size);
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
StringSource( reinterpret_cast<const char *>(decodedKey), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
memset( iv, 0x00, AES::BLOCKSIZE );
CBC_Mode<AES>::Encryption Encryptor( key, sizeof(key), iv );
StringSource( plain, true, new StreamTransformationFilter( Encryptor,
new HexEncoder(new StringSink( ciphertext )) ) );
return QString::fromStdString(ciphertext);
}
QString AesUtils::decrypt(QString message, QString aesKey)
{
string plain;
string encrypted = message.toStdString();
// Hex decode symmetric key:
HexDecoder decoder;
string stdAesKey = aesKey.toStdString();
decoder.Put( (byte *)stdAesKey.data(), aesKey.size() );
decoder.MessageEnd();
word64 size = decoder.MaxRetrievable();
char *decodedKey = new char[size];
decoder.Get((byte *)decodedKey, size);
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
StringSource( reinterpret_cast<const char *>(decodedKey), true,
new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
memset( iv, 0x00, AES::BLOCKSIZE );
try {
CBC_Mode<AES>::Decryption Decryptor
( key, sizeof(key), iv );
StringSource( encrypted, true,
new HexDecoder(new StreamTransformationFilter( Decryptor,
new StringSink( plain )) ) );
}
catch (Exception &e) { // ...
qDebug() << "Exception while decrypting " << e.GetWhat().data();
}
catch (...) { // ...
}
qDebug() << "decrypt" << plain.data() << " " << AES::BLOCKSIZE;
return QString::fromStdString(plain);
}
问题是我随机得到:
StreamTransformationFilter: invalid PKCS #7 block padding found
解密内容时。加密应完全支持QString
,
因为它可能包含一些Unicode数据。但即使是基本的,它也不起作用,
只包含[A-z] [a-z] [0-9]
aesKey
大小为256。
关于Stack Overflow的一些答案,有人建议使用HexDecoder
/ HexEncoder
,但在我的情况下它并没有解决问题。
答案 0 :(得分:0)
我的代码的第一个问题是我在aesKey QString中输入了正常的字符串。
因此,您需要以十六进制格式提供密钥而不是“1231fsdf $ 5r4”:[0-9] [A-F]
然后,问题在于:
char *decodedKey = new char[size];
decoder.Get((byte *)decodedKey, size);
我猜这个字符串是64个字节,最后没有空格。在我改为:
后,问题消失了char *decodedKey = new char[size+2];
现在代码工作正常。希望这将有助于将来的某些人。