Function which returns HMAC-SHA1 encrypted signature composed of public key and secret base string:

  1. QString hmacSha1(QByteArray key, QByteArray baseString)
  2. {
  3.     int blockSize = 64; // HMAC-SHA-1 block size, defined in SHA-1 standard
  4.     if (key.length() > blockSize) { // if key is longer than block size (64), reduce key length with SHA-1 compression
  5.         key = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
  6.     }
  7.  
  8.     QByteArray innerPadding(blockSize, char(0x36)); // initialize inner padding with char "6"
  9.     QByteArray outerPadding(blockSize, char(0x5c)); // initialize outer padding with char "\"
  10.     // ascii characters 0x36 ("6") and 0x5c ("\") are selected because they have large
  11.     // Hamming distance (http://en.wikipedia.org/wiki/Hamming_distance)
  12.  
  13.     for (int i = 0; i < key.length(); i++) {
  14.         innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length
  15.         outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length
  16.     }
  17.  
  18.     // result = hash ( outerPadding CONCAT hash ( innerPadding CONCAT baseString ) ).toBase64
  19.     QByteArray total = outerPadding;
  20.     QByteArray part = innerPadding;
  21.     part.append(baseString);
  22.     total.append(QCryptographicHash::hash(part, QCryptographicHash::Sha1));
  23.     QByteArray hashed = QCryptographicHash::hash(total, QCryptographicHash::Sha1);
  24.     return hashed.toBase64();
  25. }

Categories: