2 * KQOAuth - An OAuth authentication library for Qt.
4 * Author: Johan Paul (johan.paul@d-pointer.com)
5 * http://www.d-pointer.com
7 * KQOAuth is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * KQOAuth is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with KQOAuth. If not, see <http://www.gnu.org/licenses/>.
21 #include <QCryptographicHash>
25 #include "kqoauthutils.h"
27 QString KQOAuthUtils::hmac_sha1(const QString &message, const QString &key)
29 QByteArray keyBytes = key.toAscii();
30 int keyLength; // Lenght of key word
31 const int blockSize = 64; // Both MD5 and SHA-1 have a block size of 64.
33 keyLength = keyBytes.size();
34 // If key is longer than block size, we need to hash the key
35 if (keyLength > blockSize) {
36 QCryptographicHash hash(QCryptographicHash::Sha1);
37 hash.addData(keyBytes);
38 keyBytes = hash.result();
41 /* http://tools.ietf.org/html/rfc2104 - (1) */
42 // Create the opad and ipad for the hash function.
46 ipad.fill( 0, blockSize);
47 opad.fill( 0, blockSize);
49 ipad.replace(0, keyBytes.length(), keyBytes);
50 opad.replace(0, keyBytes.length(), keyBytes);
52 /* http://tools.ietf.org/html/rfc2104 - (2) & (5) */
53 for (int i=0; i<64; i++) {
54 ipad[i] = ipad[i] ^ 0x36;
55 opad[i] = opad[i] ^ 0x5c;
61 workArray.append(ipad, 64);
62 /* http://tools.ietf.org/html/rfc2104 - (3) */
63 workArray.append(message.toAscii());
66 /* http://tools.ietf.org/html/rfc2104 - (4) */
67 QByteArray sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
69 /* http://tools.ietf.org/html/rfc2104 - (6) */
71 workArray.append(opad, 64);
72 workArray.append(sha1);
76 /* http://tools.ietf.org/html/rfc2104 - (7) */
77 sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
78 return QString(sha1.toBase64());