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>
20 m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
25 Cipher::Cipher(QByteArray key, QString cipherType)
27 m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
36 bool Cipher::setKey(QByteArray key)
43 if (key.mid(0, 4).toLower() == "ecb:")
48 //strip cbc: if included
49 else if (key.mid(0, 4).toLower() == "cbc:")
56 // if(Preferences::self()->encryptionType())
66 bool Cipher::setType(const QString &type)
68 //TODO check QCA::isSupported()
74 QByteArray Cipher::decrypt(QByteArray cipherText)
77 bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
80 if (cipherText.mid(0, 5) == "+OK *")
84 cipherText = cipherText.mid(5);
88 cipherText = cipherText.mid(5);
89 pfx = "ERROR_NONECB: ";
94 else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ")
99 cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
100 pfx = "ERROR_NONCBC: ";
106 if (cipherText.mid(0, 4) == "+OK ")
107 cipherText = cipherText.mid(4);
109 cipherText = cipherText.mid(5);
112 //all other cases we fail
117 // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
118 if ((m_cbc && !error) || (!m_cbc && error))
120 cipherText = cipherText;
121 temp = blowfishCBC(cipherText, false);
123 if (temp == cipherText)
125 // kDebug("Decryption from CBC Failed");
126 return cipherText+' '+'\n';
133 temp = blowfishECB(cipherText, false);
135 if (temp == cipherText)
137 // kDebug("Decryption from ECB Failed");
138 return cipherText+' '+'\n';
143 // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick>
144 // don't hate me for the mircryption reference there.
145 if (cipherText.at(0) == 1)
147 cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here?
152 QByteArray Cipher::initKeyExchange()
154 QCA::Initializer init;
155 m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH();
157 if (m_tempKey.isNull())
160 QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray();
163 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
164 publicKey = publicKey.mid(1);
166 return publicKey.toBase64().append('A');
170 QByteArray Cipher::parseInitKeyX(QByteArray key)
172 QCA::Initializer init;
175 if (key.endsWith(" CBC"))
181 if (key.length() != 181)
184 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
185 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
186 QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();
188 if (privateKey.isNull())
191 QByteArray publicKey = privateKey.y().toArray().toByteArray();
194 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
195 publicKey = publicKey.mid(1);
197 QCA::DHPublicKey remotePub(group, remoteKey);
199 if (remotePub.isNull())
202 QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
203 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
205 //remove trailing = because mircryption and fish think it's a swell idea.
206 while (sharedKey.endsWith('=')) sharedKey.chop(1);
209 sharedKey.prepend("cbc:");
211 bool success = setKey(sharedKey);
216 return publicKey.toBase64().append('A');
220 bool Cipher::parseFinishKeyX(QByteArray key)
222 QCA::Initializer init;
224 if (key.length() != 181)
227 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
228 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
230 QCA::DHPublicKey remotePub(group, remoteKey);
232 if (remotePub.isNull())
235 if (m_tempKey.isNull())
238 QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
239 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
241 //remove trailng = because mircryption and fish think it's a swell idea.
242 while (sharedKey.endsWith('=')) sharedKey.chop(1);
244 bool success = setKey(sharedKey);
250 QByteArray Cipher::decryptTopic(QByteArray cipherText)
252 if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
253 cipherText = cipherText.mid(4);
254 else if (cipherText.left(5) == "«m«")
255 cipherText = cipherText.mid(5, cipherText.length()-10);
260 //TODO currently no backwards sanity checks for topic, it seems to use different standards
261 //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
263 temp = blowfishCBC(cipherText.mid(1), false);
265 temp = blowfishECB(cipherText, false);
267 if (temp == cipherText)
274 if (cipherText.mid(0, 2) == "@@")
275 cipherText = cipherText.mid(2);
281 bool Cipher::encrypt(QByteArray &cipherText)
283 if (cipherText.left(3) == "+p ") //don't encode if...?
284 cipherText = cipherText.mid(3);
287 if (m_cbc) //encode in ecb or cbc decide how to determine later
289 QByteArray temp = blowfishCBC(cipherText, true);
291 if (temp == cipherText)
293 // kDebug("CBC Encoding Failed");
297 cipherText = "+OK *" + temp;
301 QByteArray temp = blowfishECB(cipherText, true);
303 if (temp == cipherText)
305 // kDebug("ECB Encoding Failed");
309 cipherText = "+OK " + temp;
316 //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
317 QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
319 QCA::Initializer init;
320 QByteArray temp = cipherText;
323 // make sure cipherText is an interval of 8 bits. We do this before so that we
324 // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
325 while ((temp.length() % 8) != 0) temp.append('\0');
327 QCA::InitializationVector iv(8);
328 temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
332 temp = QByteArray::fromBase64(temp);
333 //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
334 //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
335 while ((temp.length() % 8) != 0) temp.append('\0');
338 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
339 QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
340 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
341 temp2 += cipher.final().toByteArray();
346 if (direction) //send in base64
347 temp2 = temp2.toBase64();
348 else //cut off the 8bits of IV
349 temp2 = temp2.remove(0, 8);
355 QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
357 QCA::Initializer init;
358 QByteArray temp = cipherText;
360 //do padding ourselves
363 while ((temp.length() % 8) != 0) temp.append('\0');
367 // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
368 if ((temp.length() % 12) != 0)
371 temp = b64ToByte(temp);
372 while ((temp.length() % 8) != 0) temp.append('\0');
375 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
376 QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
377 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
378 temp2 += cipher.final().toByteArray();
385 if ((temp2.length() % 8) != 0)
388 temp2 = byteToB64(temp2);
395 //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
396 QByteArray Cipher::byteToB64(QByteArray text)
402 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
404 while (k < (text.length() - 1)) {
406 v = text.at(k); if (v < 0) v += 256;
409 v = text.at(k); if (v < 0) v += 256;
412 v = text.at(k); if (v < 0) v += 256;
415 v = text.at(k); if (v < 0) v += 256;
419 v = text.at(k); if (v < 0) v += 256;
422 v = text.at(k); if (v < 0) v += 256;
425 v = text.at(k); if (v < 0) v += 256;
428 v = text.at(k); if (v < 0) v += 256;
431 for (int i = 0; i < 6; i++) {
432 encoded.append(base64.at(right & 0x3F).toLatin1());
436 //TODO make sure the .toLatin1 doesn't break anything
437 for (int i = 0; i < 6; i++) {
438 encoded.append(base64.at(left & 0x3F).toLatin1());
446 QByteArray Cipher::b64ToByte(QByteArray text)
448 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
451 while (k < (text.length() - 1)) {
458 for (int i = 0; i < 6; i++) {
460 v = base64.indexOf(text.at(k));
461 right |= v << (i * 6);
464 for (int i = 0; i < 6; i++) {
466 v = base64.indexOf(text.at(k));
467 left |= v << (i * 6);
470 for (int i = 0; i < 4; i++) {
471 w = ((left & (0xFF << ((3 - i) * 8))));
472 z = w >> ((3 - i) * 8);
473 if (z < 0) { z = z + 256; }
477 for (int i = 0; i < 4; i++) {
478 w = ((right & (0xFF << ((3 - i) * 8))));
479 z = w >> ((3 - i) * 8);
480 if (z < 0) { z = z + 256; }
488 bool Cipher::neededFeaturesAvailable()
490 QCA::Initializer init;
492 if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh"))