我有以下代码可以加密和解密消息。
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 数据。但即使使用仅包含 [Az][az][0-9] 的基本字符串,它也不起作用
aesKey
大小为 256 。
在 Stack Overflow 上的一些答案之后,有人建议使用HexDecoder
/ HexEncoder
,但它并不能解决我的问题。