d6518a7a28109248d79eb148562db94f23b95658
[googlelatitude] / libkqoauth / kqoauthutils.cpp
1 /**
2  * KQOAuth - An OAuth authentication library for Qt.
3  *
4  * Author: Johan Paul (johan.paul@d-pointer.com)
5  *         http://www.d-pointer.com
6  *
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.
11  *
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.
16  *
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/>.
19  */
20 #include <QString>
21 #include <QCryptographicHash>
22 #include <QByteArray>
23
24 #include <QtDebug>
25 #include "kqoauthutils.h"
26
27 QString KQOAuthUtils::hmac_sha1(const QString &message, const QString &key)
28 {
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.
32
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();
39     }
40
41     /* http://tools.ietf.org/html/rfc2104  - (1) */
42     // Create the opad and ipad for the hash function.
43     QByteArray ipad;
44     QByteArray opad;
45
46     ipad.fill( 0, blockSize);
47     opad.fill( 0, blockSize);
48
49     ipad.replace(0, keyBytes.length(), keyBytes);
50     opad.replace(0, keyBytes.length(), keyBytes);
51
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;
56     }
57
58     QByteArray workArray;
59     workArray.clear();
60
61     workArray.append(ipad, 64);
62     /* http://tools.ietf.org/html/rfc2104 - (3) */
63     workArray.append(message.toAscii());
64
65
66     /* http://tools.ietf.org/html/rfc2104 - (4) */
67     QByteArray sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
68
69     /* http://tools.ietf.org/html/rfc2104 - (6) */
70     workArray.clear();
71     workArray.append(opad, 64);
72     workArray.append(sha1);
73
74     sha1.clear();
75
76     /* http://tools.ietf.org/html/rfc2104 - (7) */
77     sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1);
78     return QString(sha1.toBase64());
79 }