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)
41 if (key.mid(0, 4).toLower() == "ecb:")
46 //strip cbc: if included
47 else if (key.mid(0, 4).toLower() == "cbc:")
54 // if(Preferences::self()->encryptionType())
64 bool Cipher::setType(const QString &type)
66 //TODO check QCA::isSupported()
72 QByteArray Cipher::decrypt(QByteArray cipherText)
75 bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
78 if (cipherText.mid(0, 5) == "+OK *")
82 cipherText = cipherText.mid(5);
86 cipherText = cipherText.mid(5);
87 pfx = "ERROR_NONECB: ";
92 else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ")
97 cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
98 pfx = "ERROR_NONCBC: ";
104 if (cipherText.mid(0, 4) == "+OK ")
105 cipherText = cipherText.mid(4);
107 cipherText = cipherText.mid(5);
110 //all other cases we fail
115 // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
116 if ((m_cbc && !error) || (!m_cbc && error))
118 cipherText = cipherText;
119 temp = blowfishCBC(cipherText, false);
121 if (temp == cipherText)
123 // kDebug("Decryption from CBC Failed");
124 return cipherText+' '+'\n';
131 temp = blowfishECB(cipherText, false);
133 if (temp == cipherText)
135 // kDebug("Decryption from ECB Failed");
136 return cipherText+' '+'\n';
141 // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick>
142 // don't hate me for the mircryption reference there.
143 if (cipherText.at(0) == 1)
145 cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here?
150 QByteArray Cipher::initKeyExchange()
152 QCA::Initializer init;
153 m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH();
155 if (m_tempKey.isNull())
158 QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray();
161 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
162 publicKey = publicKey.mid(1);
164 return publicKey.toBase64().append('A');
168 QByteArray Cipher::parseInitKeyX(QByteArray key)
170 QCA::Initializer init;
172 if (key.length() != 181)
175 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
176 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
177 QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH();
179 if (privateKey.isNull())
182 QByteArray publicKey = privateKey.y().toArray().toByteArray();
185 if (publicKey.length() > 135 && publicKey.at(0) == '\0')
186 publicKey = publicKey.mid(1);
188 QCA::DHPublicKey remotePub(group, remoteKey);
190 if (remotePub.isNull())
193 QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
194 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
196 //remove trailing = because mircryption and fish think it's a swell idea.
197 while (sharedKey.endsWith('=')) sharedKey.chop(1);
199 bool success = setKey(sharedKey);
204 return publicKey.toBase64().append('A');
208 bool Cipher::parseFinishKeyX(QByteArray key)
210 QCA::Initializer init;
212 if (key.length() != 181)
215 QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180));
216 QCA::DLGroup group(m_primeNum, QCA::BigInteger(2));
218 QCA::DHPublicKey remotePub(group, remoteKey);
220 if (remotePub.isNull())
223 if (m_tempKey.isNull())
226 QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
227 sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
229 //remove trailng = because mircryption and fish think it's a swell idea.
230 while (sharedKey.endsWith('=')) sharedKey.chop(1);
232 bool success = setKey(sharedKey);
238 QByteArray Cipher::decryptTopic(QByteArray cipherText)
240 if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
241 cipherText = cipherText.mid(4);
242 else if (cipherText.left(5) == "«m«")
243 cipherText = cipherText.mid(5, cipherText.length()-10);
248 //TODO currently no backwards sanity checks for topic, it seems to use different standards
249 //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
251 temp = blowfishCBC(cipherText.mid(1), false);
253 temp = blowfishECB(cipherText, false);
255 if (temp == cipherText)
262 if (cipherText.mid(0, 2) == "@@")
263 cipherText = cipherText.mid(2);
269 bool Cipher::encrypt(QByteArray &cipherText)
271 if (cipherText.left(3) == "+p ") //don't encode if...?
272 cipherText = cipherText.mid(3);
275 if (m_cbc) //encode in ecb or cbc decide how to determine later
277 QByteArray temp = blowfishCBC(cipherText, true);
279 if (temp == cipherText)
281 // kDebug("CBC Encoding Failed");
285 cipherText = "+OK *" + temp;
289 QByteArray temp = blowfishECB(cipherText, true);
291 if (temp == cipherText)
293 // kDebug("ECB Encoding Failed");
297 cipherText = "+OK " + temp;
304 //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
305 QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
307 QCA::Initializer init;
308 QByteArray temp = cipherText;
311 // make sure cipherText is an interval of 8 bits. We do this before so that we
312 // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
313 while ((temp.length() % 8) != 0) temp.append('\0');
315 QCA::InitializationVector iv(8);
316 temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
320 temp = QByteArray::fromBase64(temp);
321 //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
322 //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
323 while ((temp.length() % 8) != 0) temp.append('\0');
326 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
327 QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
328 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
329 temp2 += cipher.final().toByteArray();
334 if (direction) //send in base64
335 temp2 = temp2.toBase64();
336 else //cut off the 8bits of IV
337 temp2 = temp2.remove(0, 8);
343 QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
345 QCA::Initializer init;
346 QByteArray temp = cipherText;
348 //do padding ourselves
351 while ((temp.length() % 8) != 0) temp.append('\0');
355 temp = b64ToByte(temp);
356 while ((temp.length() % 8) != 0) temp.append('\0');
359 QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
360 QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
361 QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
362 temp2 += cipher.final().toByteArray();
368 temp2 = byteToB64(temp2);
374 //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
375 QByteArray Cipher::byteToB64(QByteArray text)
381 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
383 while (k < (text.length() - 1)) {
385 v = text.at(k); if (v < 0) v += 256;
388 v = text.at(k); if (v < 0) v += 256;
391 v = text.at(k); if (v < 0) v += 256;
394 v = text.at(k); if (v < 0) v += 256;
398 v = text.at(k); if (v < 0) v += 256;
401 v = text.at(k); if (v < 0) v += 256;
404 v = text.at(k); if (v < 0) v += 256;
407 v = text.at(k); if (v < 0) v += 256;
410 for (int i = 0; i < 6; i++) {
411 encoded.append(base64.at(right & 0x3F).toAscii());
415 //TODO make sure the .toascii doesn't break anything
416 for (int i = 0; i < 6; i++) {
417 encoded.append(base64.at(left & 0x3F).toAscii());
425 QByteArray Cipher::b64ToByte(QByteArray text)
427 QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
430 while (k < (text.length() - 1)) {
437 for (int i = 0; i < 6; i++) {
439 v = base64.indexOf(text.at(k));
440 right |= v << (i * 6);
443 for (int i = 0; i < 6; i++) {
445 v = base64.indexOf(text.at(k));
446 left |= v << (i * 6);
449 for (int i = 0; i < 4; i++) {
450 w = ((left & (0xFF << ((3 - i) * 8))));
451 z = w >> ((3 - i) * 8);
452 if (z < 0) { z = z + 256; }
456 for (int i = 0; i < 4; i++) {
457 w = ((right & (0xFF << ((3 - i) * 8))));
458 z = w >> ((3 - i) * 8);
459 if (z < 0) { z = z + 256; }
467 bool Cipher::neededFeaturesAvailable()
469 QCA::Initializer init;
471 if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh"))
474 qWarning() << "QCA provider plugin not found. It is usually provided by the qca-ossl plugin.";