Friday, February 26, 2010

QCryptographicHash: code snippet

  When the guys developing Qt applications find themselves in such a case when they need to obtain MD5 hash of a string or an array of bytes, the first thing most of them do is try to use the already implemented 3rd-party libraries like libxcrypt, OpenSSL and others. The talented ones try to get the output of 'md5sum' command.
  But the 'true' way is to use built-in tools: not everyone knows that Qt already has QCryptographicHash class which can help us. Let's see how:


QString password("our super secret password");
QByteArray hashed_password_ba(
     QCryptographicHash::hash(password.toAscii(),
                              QCryptographicHash::Md5));
/* Now 'md5_password' var contains
*  md5-hashed our super secret password 
*/
QString md5_password(hashed_password_ba.toHex().constData());

Very easy, isn't it? Apart from MD5, the class allows to generate MD4 and Sha1 hashes which may also be very helpful in some special cases.

3 comments:

  1. that is the shortest solution what i found and it works fantastic

    thx

    ReplyDelete
  2. How do we do the reverse? An application should be able to encrypt a "string" via the above procedure and later should be able decrypt, too.

    ReplyDelete
  3. @Amit: There is no way to decrypt it because hash algorithms supposed to be the only one way. You should use 3rd-party libraries or implement your own algorithm (e.g. via XOR :)).

    ReplyDelete