Having trouble decrypting a well-formed cipher text using Crypto++

好久不见. 提交于 2019-11-28 14:10:27

Full source codes of those function can be found on my repo on GitHub

I'd make these changes at minimum:

QString CryptoUtils::encrypt(QString text, QString keyhex)
{
    ...

    // name the variable, kill the memory leak
    SHA256 sha256;
    StringSource ss1(decodedKey, size, true, new HashFilter(sha256, new ArraySink(key, AES::MAX_KEYLENGTH)));
    ...

    // name the variable
    StringSource ss2(plain, true, new StreamTransformationFilter(Encryptor, new HexEncoder(new StringSink(encrypted))));

    // verify embedded NULLs don't affect results
    QString qs = QString::fromStdString(encrypted);
    assert(qs.length() == encrypted.length());
}

And:

QString CryptoUtils::decrypt(QString text, QString keyhex)
{
    // bad karma here...
    string encrypted = text.toStdString();
    assert(encrypted.length() == text.length());
    ...

    // name the variable, kill the memory leak
    SHA256 sha256;
    StringSource ss1(decodedKey, size, true, new HashFilter(sha256, new ArraySink(key, AES::MAX_KEYLENGTH)));
    ...

    // name the variable,
    StringSource ss2(encrypted, true, new HexDecoder(new StreamTransformationFilter(Decryptor, new StringSink(plain))));

    // verify embedded NULLs don't affect results
    QString qs = QString::fromStdString(plain);
    assert(qs.length() == plain.length());
}

The hexEncode function seems to misbehave:

QString CryptoUtils::hexEncode(QString text)
{
    byte *bytearray = (byte *) text.toLatin1().data();
    int length = text.toLatin1().length();

    return hexEncode(bytearray, length);
}

Should be replaced with:

QString CryptoUtils::hexEncode(QString text)
{
    byte *bytearray = (byte *) text.toStdString().data();
    int length = text.length();

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