My Programming projects and other stuff.
HMAC hash for Qt

Some authentication services like Twitters needs HMAC-SHA1 cryptographic hashing, that qt libraries don’t offer yet. Here is a my piece of code I wrote when I made Twitter authentication last year:

First read about HMAC:

and here is the code:

   * Hashes the given string using the HMAC-SHA1 algorithm.
   * \param key The string to be hashed
   * \param secret The string that contains secret word
   * \return The hashed string
   static QString hmac_sha1(const QString &key, 
                          const QString &secret)
      //Length of the text, that will be hashed
      int	text_lenght;
      //For secret word.
      QByteArray K;
      //Lenght of secret word
      int	K_lenght;
      K_lenght = secret.size();
      text_lenght = key.size();
      //Need to do for XOR operation. Transforms QString to
      //unsigned char
      K = secret.toAscii();
      //Inner padding
      QByteArray ipad;
      //Outer pad
      QByteArray opad;
      //if secret key > 64 bytes use this to obtain sha1 key
      if(K_lenght > 64)
         QByteArray tempSecret;
         K = QCryptographicHash::hash(tempSecret, 
         K_lenght = 20;
      //Fills ipad and opad with zeros
      //bzero( ipad, sizeof ipad);
      //bzero( opad, sizeof opad);
      ipad.fill( 0, 64);
      opad.fill(0, 64);
      //Copies Secret to ipad and opad
      //bcopy( K, ipad, K_lenght);
      //bcopy( K, opad, K_lenght);
      ipad.replace(0, K_lenght, K);
      opad.replace(0, K_lenght, K);
      //XOR operation for inner and outer pad
      for (int i=0; i<64; i++)
         ipad[i] = ipad[i] ^ 0x36;
         opad[i] = opad[i] ^ 0x5c;
      //Stores hashed content
      QByteArray context;
      //Appends XOR:ed ipad to context
      //Appends key to context
      //Hashes Inner pad
      QByteArray Sha1	= QCryptographicHash::hash(context,
      //Appends opad to context
      //Appends hashed inner pad to context
      // Hashes outerpad
      Sha1 = QCryptographicHash::hash(context,
      // String to return hashed stuff in Base64 format
      QByteArray str(Sha1.toBase64());
      return str;
  1. mahonen posted this