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;
174 if (key.length() != 181)
177 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
178 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
179 QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();
181 if (privateKey.isNull())
184 QByteArray publicKey = privateKey.y().toArray().toByteArray();
187 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
188 publicKey = publicKey.mid(1);
190 QCA::DHPublicKey remotePub(group, remoteKey);
192 if (remotePub.isNull())
195 QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
196 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
198 //remove trailing = because mircryption and fish think it's a swell idea.
199 while (sharedKey.endsWith('=')) sharedKey.chop(1);
201 bool success = setKey(sharedKey);
206 return publicKey.toBase64().append('A');
210 bool Cipher::parseFinishKeyX(QByteArray key)
212 QCA::Initializer init;
214 if (key.length() != 181)
217 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
218 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
220 QCA::DHPublicKey remotePub(group, remoteKey);
222 if (remotePub.isNull())
225 if (m_tempKey.isNull())
228 QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
229 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
231 //remove trailng = because mircryption and fish think it's a swell idea.
232 while (sharedKey.endsWith('=')) sharedKey.chop(1);
234 bool success = setKey(sharedKey);
240 QByteArray Cipher::decryptTopic(QByteArray cipherText)
242 if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
243 cipherText = cipherText.mid(4);
244 else if (cipherText.left(5) == "«m«")
245 cipherText = cipherText.mid(5, cipherText.length()-10);
250 //TODO currently no backwards sanity checks for topic, it seems to use different standards
251 //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
253 temp = blowfishCBC(cipherText.mid(1), false);
255 temp = blowfishECB(cipherText, false);
257 if (temp == cipherText)
264 if (cipherText.mid(0, 2) == "@@")
265 cipherText = cipherText.mid(2);
271 bool Cipher::encrypt(QByteArray &cipherText)
273 if (cipherText.left(3) == "+p ") //don't encode if...?
274 cipherText = cipherText.mid(3);
277 if (m_cbc) //encode in ecb or cbc decide how to determine later
279 QByteArray temp = blowfishCBC(cipherText, true);
281 if (temp == cipherText)
283 // kDebug("CBC Encoding Failed");
287 cipherText = "+OK *" + temp;
291 QByteArray temp = blowfishECB(cipherText, true);
293 if (temp == cipherText)
295 // kDebug("ECB Encoding Failed");
299 cipherText = "+OK " + temp;
306 //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
307 QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
309 QCA::Initializer init;
310 QByteArray temp = cipherText;
313 // make sure cipherText is an interval of 8 bits. We do this before so that we
314 // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
315 while ((temp.length() % 8) != 0) temp.append('\0');
317 QCA::InitializationVector iv(8);
318 temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
322 temp = QByteArray::fromBase64(temp);
323 //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
324 //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
325 while ((temp.length() % 8) != 0) temp.append('\0');
328 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
329 QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
330 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
331 temp2 += cipher.final().toByteArray();
336 if (direction) //send in base64
337 temp2 = temp2.toBase64();
338 else //cut off the 8bits of IV
339 temp2 = temp2.remove(0, 8);
345 QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
347 QCA::Initializer init;
348 QByteArray temp = cipherText;
350 //do padding ourselves
353 while ((temp.length() % 8) != 0) temp.append('\0');
357 temp = b64ToByte(temp);
358 while ((temp.length() % 8) != 0) temp.append('\0');
361 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
362 QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
363 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
364 temp2 += cipher.final().toByteArray();
370 temp2 = byteToB64(temp2);
376 //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
377 QByteArray Cipher::byteToB64(QByteArray text)
383 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
385 while (k < (text.length() - 1)) {
387 v = text.at(k); if (v < 0) v += 256;
390 v = text.at(k); if (v < 0) v += 256;
393 v = text.at(k); if (v < 0) v += 256;
396 v = text.at(k); if (v < 0) v += 256;
400 v = text.at(k); if (v < 0) v += 256;
403 v = text.at(k); if (v < 0) v += 256;
406 v = text.at(k); if (v < 0) v += 256;
409 v = text.at(k); if (v < 0) v += 256;
412 for (int i = 0; i < 6; i++) {
413 encoded.append(base64.at(right & 0x3F).toAscii());
417 //TODO make sure the .toascii doesn't break anything
418 for (int i = 0; i < 6; i++) {
419 encoded.append(base64.at(left & 0x3F).toAscii());
427 QByteArray Cipher::b64ToByte(QByteArray text)
429 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
432 while (k < (text.length() - 1)) {
439 for (int i = 0; i < 6; i++) {
441 v = base64.indexOf(text.at(k));
442 right |= v << (i * 6);
445 for (int i = 0; i < 6; i++) {
447 v = base64.indexOf(text.at(k));
448 left |= v << (i * 6);
451 for (int i = 0; i < 4; i++) {
452 w = ((left & (0xFF << ((3 - i) * 8))));
453 z = w >> ((3 - i) * 8);
454 if (z < 0) { z = z + 256; }
458 for (int i = 0; i < 4; i++) {
459 w = ((right & (0xFF << ((3 - i) * 8))));
460 z = w >> ((3 - i) * 8);
461 if (z < 0) { z = z + 256; }
469 bool Cipher::neededFeaturesAvailable()
471 QCA::Initializer init;
473 if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh"))
476 qWarning() << "QCA provider plugin not found. It is usually provided by the qca-ossl plugin.";