Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Converting QByteArray to QString after hashing



  • Hello everyone!
    I am trying to use the QCryptographicHash library for my application, but in testing it I have a problem. After hashing, when I try to get the hashed QByteArray to QString and show it in the console I get a weird string.
    Code:

    #include <QCoreApplication>
    #include <QCryptographicHash>
    #include <QDebug>
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString input="helloworld";
        QByteArray result=QCryptographicHash::hash(input.toLocal8Bit(), QCryptographicHash::Md5);
        QString inputHash=QString::fromLocal8Bit(result);
        qDebug() << input << " " << input.length();
        qDebug() << inputHash << " " << inputHash.length();
    }
    

    What am I doing wrong and how can I get the correct string?


  • Qt Champions 2019

    The hash function returns a QByteArray which is not printable - it's a hash.
    You can use QByteArray::toHex() to represent the data as hex values.



  • I see. But do you have any suggestion about what should I do now?

    I need a user to be able to input a string in a lineEdit and I want to save the converted, hashed string in an online database. I need to obtain strings as I would obtain from this site for example: MD5 Online Hasher

    The algorithm doesn't have to be MD5, I would just want to use one of Qt's in-built features.


  • Lifetime Qt Champion

    @Paul-Orasan

    Just like @Christian-Ehrlicher said, with toHex():

    #include <QCryptographicHash>
    #include <QDebug>
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString input = "helloworld";
        QByteArray result = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Md5);
        QString inputHash = QLatin1String(result.toHex());
        qDebug() << input << " " << input.length();
        qDebug() << inputHash << " " << inputHash.length();
    }
    

    Note that I did two changes to your code:

    1. I use input.toUtf8() to get the same hash always. Otherwise you can get different outputs depending on the users platform or region
    2. The result contains only ASCII after toHex(), so QLatin1String is the fastest conversion to QString

    Regards


Log in to reply