AES 256 encryption - Qt equivalent for Java

断了今生、忘了曾经 提交于 2019-11-30 15:37:06

I guess your Java implementation misses a hash step on the key. I'm using a SHA256 hash of the key. To test c++ implementation, change code to this:

QString encrypt(QByteArray r, const QString &password)
 {
const char *sample = r.data();
string plain = password.toStdString();
string ciphertext;
// Generate Cipher, Key, and CBC
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ];
//StringSource( reinterpret_cast<const char *>(sample), true,
//              new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH)) );
for(int i=0; i< AES::MAX_KEYLENGTH; ++i){
    key[i] = reinterpret_cast<const char *>(decodedKey)[i];
}
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);
} 

Initialization vector is different in your Java code and Qt:

private static final byte[] IV = {
    0, 2, 4, 8, 16, 32, 64, 127, 
    127, 64, 32, 16, 8, 4, 2, 0
};

And in C++:

memset( iv, 0x00, AES::BLOCKSIZE ); // ==> This fills the iv array with 0s

So you need to use same IV for both schemes.

Update:

In order to provide an IV for CBC mode of AES, you need to specify IV as you do in Java:

byte iv[ AES::BLOCKSIZE ] = {0, 2, 4, 8, 16, 32, 64, 127, 
                             127, 64, 32, 16, 8, 4, 2, 0};

Note that AES::BLOCKSIZE is defined in library headers and it is 16.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!