2 This file has been derived from Konversation, the KDE IRC client.
3 You can redistribute it and/or modify it under the terms of the
4 GNU General Public License as published by the Free Software Foundation;
5 either version 2 of the License, or (at your option) any later version.
9 Copyright (C) 1997 Robey Pointer <robeypointer@gmail.com>
10 Copyright (C) 2005 Ismail Donmez <ismail@kde.org>
11 Copyright (C) 2009 Travis McHenry <tmchenryaz@cox.net>
12 Copyright (C) 2009 Johannes Huber <johu@gmx.de>
19 m_primeNum = QCA::BigInteger(
20 "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095"
21 "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862"
22 "335062591404043092163187352352197487303798807791605274487594646923");
26 Cipher::Cipher(QByteArray key, QString cipherType)
28 m_primeNum = QCA::BigInteger(
29 "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095"
30 "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862"
31 "335062591404043092163187352352197487303798807791605274487594646923");
36 bool Cipher::setKey(QByteArray key)
43 if (key.mid(0, 4).toLower() == "ecb:") {
47 // strip cbc: if included
48 else if (key.mid(0, 4).toLower() == "cbc:") {
53 // if(Preferences::self()->encryptionType())
63 bool Cipher::setType(const QString& type)
65 // TODO check QCA::isSupported()
70 QByteArray Cipher::decrypt(QByteArray cipherText)
73 bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
76 if (cipherText.mid(0, 5) == "+OK *") {
79 cipherText = cipherText.mid(5);
82 cipherText = cipherText.mid(5);
83 pfx = "ERROR_NONECB: ";
88 else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") {
91 cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
92 pfx = "ERROR_NONCBC: ";
97 if (cipherText.mid(0, 4) == "+OK ")
98 cipherText = cipherText.mid(4);
100 cipherText = cipherText.mid(5);
103 // all other cases we fail
108 // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
109 if ((m_cbc && !error) || (!m_cbc && error)) {
110 temp = blowfishCBC(cipherText, false);
112 if (temp == cipherText) {
113 // kDebug("Decryption from CBC Failed");
114 return cipherText + ' ' + '\n';
120 temp = blowfishECB(cipherText, false);
122 if (temp == cipherText) {
123 // kDebug("Decryption from ECB Failed");
124 return cipherText + ' ' + '\n';
129 // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick>
130 // don't hate me for the mircryption reference there.
131 if (cipherText.at(0) == 1)
133 cipherText = pfx + cipherText + ' ' + '\n'; // FIXME(??) why is there an added space here?
137 QByteArray Cipher::initKeyExchange()
139 QCA::Initializer init;
140 m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH();
142 if (m_tempKey.isNull())
145 QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray();
148 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
149 publicKey = publicKey.mid(1);
151 return publicKey.toBase64().append('A');
154 QByteArray Cipher::parseInitKeyX(QByteArray key)
156 QCA::Initializer init;
159 if (key.endsWith(" CBC")) {
164 if (key.length() != 181)
167 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
168 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
169 QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();
171 if (privateKey.isNull())
174 QByteArray publicKey = privateKey.y().toArray().toByteArray();
177 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
178 publicKey = publicKey.mid(1);
180 QCA::DHPublicKey remotePub(group, remoteKey);
182 if (remotePub.isNull())
185 QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
186 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
188 // remove trailing = because mircryption and fish think it's a swell idea.
189 while (sharedKey.endsWith('='))
193 sharedKey.prepend("cbc:");
195 bool success = setKey(sharedKey);
200 return publicKey.toBase64().append('A');
203 bool Cipher::parseFinishKeyX(QByteArray key)
205 QCA::Initializer init;
207 if (key.length() != 181)
210 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
211 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
213 QCA::DHPublicKey remotePub(group, remoteKey);
215 if (remotePub.isNull())
218 if (m_tempKey.isNull())
221 QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
222 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
224 // remove trailng = because mircryption and fish think it's a swell idea.
225 while (sharedKey.endsWith('='))
228 bool success = setKey(sharedKey);
233 QByteArray Cipher::decryptTopic(QByteArray cipherText)
235 if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
236 cipherText = cipherText.mid(4);
237 else if (cipherText.left(5) == "«m«")
238 cipherText = cipherText.mid(5, cipherText.length() - 10);
243 // TODO currently no backwards sanity checks for topic, it seems to use different standards
244 // if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
246 temp = blowfishCBC(cipherText.mid(1), false);
248 temp = blowfishECB(cipherText, false);
250 if (temp == cipherText) {
256 if (cipherText.mid(0, 2) == "@@")
257 cipherText = cipherText.mid(2);
262 bool Cipher::encrypt(QByteArray& cipherText)
264 if (cipherText.left(3) == "+p ") // don't encode if...?
265 cipherText = cipherText.mid(3);
267 if (m_cbc) // encode in ecb or cbc decide how to determine later
269 QByteArray temp = blowfishCBC(cipherText, true);
271 if (temp == cipherText) {
272 // kDebug("CBC Encoding Failed");
276 cipherText = "+OK *" + temp;
279 QByteArray temp = blowfishECB(cipherText, true);
281 if (temp == cipherText) {
282 // kDebug("ECB Encoding Failed");
286 cipherText = "+OK " + temp;
292 // THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
293 QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
295 QCA::Initializer init;
296 QByteArray temp = cipherText;
298 // make sure cipherText is an interval of 8 bits. We do this before so that we
299 // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
300 while ((temp.length() % 8) != 0)
303 QCA::InitializationVector iv(8);
304 temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
307 temp = QByteArray::fromBase64(temp);
308 // supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
309 // en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
310 while ((temp.length() % 8) != 0)
314 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
315 QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
316 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
317 temp2 += cipher.final().toByteArray();
322 if (direction) // send in base64
323 temp2 = temp2.toBase64();
324 else // cut off the 8bits of IV
325 temp2 = temp2.remove(0, 8);
330 QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
332 QCA::Initializer init;
333 QByteArray temp = cipherText;
335 // do padding ourselves
337 while ((temp.length() % 8) != 0)
341 // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
342 if ((temp.length() % 12) != 0)
345 temp = b64ToByte(temp);
346 while ((temp.length() % 8) != 0)
350 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
351 QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
352 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
353 temp2 += cipher.final().toByteArray();
360 if ((temp2.length() % 8) != 0)
363 temp2 = byteToB64(temp2);
369 // Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
370 QByteArray Cipher::byteToB64(QByteArray text)
376 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
378 while (k < (text.length() - 1)) {
421 for (int i = 0; i < 6; i++) {
422 encoded.append(base64.at(right & 0x3F).toLatin1());
426 // TODO make sure the .toLatin1 doesn't break anything
427 for (int i = 0; i < 6; i++) {
428 encoded.append(base64.at(left & 0x3F).toLatin1());
435 QByteArray Cipher::b64ToByte(QByteArray text)
437 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
440 while (k < (text.length() - 1)) {
447 for (int i = 0; i < 6; i++) {
449 v = base64.indexOf(text.at(k));
450 right |= v << (i * 6);
453 for (int i = 0; i < 6; i++) {
455 v = base64.indexOf(text.at(k));
456 left |= v << (i * 6);
459 for (int i = 0; i < 4; i++) {
460 w = ((left & (0xFF << ((3 - i) * 8))));
461 z = w >> ((3 - i) * 8);
468 for (int i = 0; i < 4; i++) {
469 w = ((right & (0xFF << ((3 - i) * 8))));
470 z = w >> ((3 - i) * 8);
480 bool Cipher::neededFeaturesAvailable()
482 QCA::Initializer init;
484 if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh"))