aboutsummaryrefslogtreecommitdiffstats
path: root/src/modules/rijndael/libkvirijndael.cpp
blob: 27c401e886d13abe99fb5180603586aecd5d2394 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//=============================================================================
//
//   File : libkvirijndael.cpp
//   Creation date : Sat Now 4 2000 15:33:12 CEST by Szymon Stefanek
//
//   This file is part of the KVIrc IRC client distribution
//   Copyright (C) 2000 Till Bush (buti@geocities.com)
//   Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your option) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "libkvirijndael.h"
#include "Rijndael.h"

#include "KviModule.h"
#include "kvi_debug.h"
#include "KviLocale.h"
#include "KviControlCodes.h"
#include "UglyBase64.h"
#include "InitVectorEngine.h"

//#warning "Other engines: mircStrip koi2win colorizer lamerizer etc.."

/*
	@doc: rijndael
	@type:
		module
	@short:
		The Rijndael cryptographic engines
	@title:
		The Rijndael module
	@body:
		The Rijndael module exports six [doc:crypt_engines]cryptographic engines[/doc] based
		on the Advanced Encryption Standard algorithm called Rijndael. Rijndael was
		originally written by Joan Daemen and Vincent Rijmen. The original Rijndael
		description is available at http://www.esat.kuleuven.ac.be/~rijmen/rijndael/.[br][br]
		It is a private key block cipher that has been designed to replace
		the widely used DES, and it should provide at least decent security against
		common attacks. Theoretically the best attack that one can perform on this cipher
		is the "brute force" attack that requires a really massive parallel computation:
		outside the capability of the common "hacker".[br][br]
		My implementation allows the usage of 128, 192 and 256 bit keys
		on 128 bit data blocks. The encrypted binary data buffer is then converted
		into an ASCII-string by using the base64 conversion or hex-digit-string representation.[br][br]
		The six engines are the six possible combinations of the key lengths and ASCII-string
		conversions.
*/

#if defined(COMPILE_CRYPT_SUPPORT) || defined(Q_MOC_RUN)
#include "KviMemory.h"
#include "KviPointerList.h"
#include "KviCryptEngineDescription.h"

static KviPointerList<KviCryptEngine> * g_pEngineList = nullptr;

KviRijndaelEngine::KviRijndaelEngine()
    : KviCryptEngine()
{
	g_pEngineList->append(this);
	m_pEncryptCipher = nullptr;
	m_pDecryptCipher = nullptr;
}

KviRijndaelEngine::~KviRijndaelEngine()
{
	g_pEngineList->removeRef(this);
	if(m_pEncryptCipher)
		delete m_pEncryptCipher;
	if(m_pDecryptCipher)
		delete m_pDecryptCipher;
}

bool KviRijndaelEngine::init(const char * encKey, int encKeyLen, const char * decKey, int decKeyLen)
{
	if(m_pEncryptCipher)
	{
		delete m_pEncryptCipher;
		m_pEncryptCipher = nullptr;
	}
	if(m_pDecryptCipher)
	{
		delete m_pDecryptCipher;
		m_pDecryptCipher = nullptr;
	}

	if(encKey && (encKeyLen > 0))
	{
		if(!(decKey && (decKeyLen > 0)))
		{
			decKey = encKey;
			decKeyLen = encKeyLen;
		} // else all
	}
	else
	{
		// no encrypt key specified...
		if(decKey && decKeyLen)
		{
			encKey = decKey;
			encKeyLen = decKeyLen;
		}
		else
		{
			// both keys missing
			setLastError(__tr2qs("Missing both encryption and decryption key: at least one is needed"));
			return false;
		}
	}

	KviCString szTmpEncryptKey = KviCString(encKey, encKeyLen);
	KviCString szTmpDecryptKey = KviCString(decKey, decKeyLen);

	m_bEncryptMode = CBC; // default mode
	m_bDecryptMode = CBC; // default mode

	if(kvi_strEqualCIN("ecb:", szTmpEncryptKey.ptr(), 4) && (szTmpEncryptKey.len() > 4))
	{
		szTmpEncryptKey.cutLeft(4);
		m_bEncryptMode = ECB;
	}
	else if(kvi_strEqualCIN("old:", szTmpEncryptKey.ptr(), 4) && (szTmpEncryptKey.len() > 4))
	{
		szTmpEncryptKey.cutLeft(4);
		m_bEncryptMode = OldCBC;
	}
	else if(kvi_strEqualCIN("cbc:", szTmpEncryptKey.ptr(), 4) && (szTmpEncryptKey.len() > 4))
	{
		szTmpEncryptKey.cutLeft(4);
	}

	if(kvi_strEqualCIN("ecb:", szTmpDecryptKey.ptr(), 4) && (szTmpDecryptKey.len() > 4))
	{
		szTmpDecryptKey.cutLeft(4);
		m_bDecryptMode = ECB;
	}
	else if(kvi_strEqualCIN("old:", szTmpDecryptKey.ptr(), 4) && (szTmpDecryptKey.len() > 4))
	{
		szTmpDecryptKey.cutLeft(4);
		m_bDecryptMode = OldCBC;
	}
	else if(kvi_strEqualCIN("cbc:", szTmpDecryptKey.ptr(), 4) && (szTmpDecryptKey.len() > 4))
	{
		szTmpDecryptKey.cutLeft(4);
	}

	int defLen = getKeyLen();

	szTmpEncryptKey.padRight(defLen);
	szTmpDecryptKey.padRight(defLen);

	m_pEncryptCipher = new Rijndael();

	int retVal = m_pEncryptCipher->init(
	    (m_bEncryptMode == ECB) ? Rijndael::ECB : Rijndael::CBC,
	    Rijndael::Encrypt,
	    (unsigned char *)szTmpEncryptKey.ptr(),
	    getKeyLenId());
	if(retVal != RIJNDAEL_SUCCESS)
	{
		delete m_pEncryptCipher;
		m_pEncryptCipher = nullptr;
		setLastErrorFromRijndaelErrorCode(retVal);
		return false;
	}

	m_pDecryptCipher = new Rijndael();
	retVal = m_pDecryptCipher->init(
	    (m_bEncryptMode == ECB) ? Rijndael::ECB : Rijndael::CBC,
	    Rijndael::Decrypt,
	    (unsigned char *)szTmpDecryptKey.ptr(),
	    getKeyLenId());
	if(retVal != RIJNDAEL_SUCCESS)
	{
		delete m_pEncryptCipher;
		m_pEncryptCipher = nullptr;
		delete m_pDecryptCipher;
		m_pDecryptCipher = nullptr;
		setLastErrorFromRijndaelErrorCode(retVal);
		return false;
	}

	return true;
}

void KviRijndaelEngine::setLastErrorFromRijndaelErrorCode(int errCode)
{
	switch(errCode)
	{
		case RIJNDAEL_SUCCESS:
			setLastError(__tr2qs("Error 0: success?"));
			break;
		case RIJNDAEL_UNSUPPORTED_MODE:
			setLastError(__tr2qs("Unsupported encryption mode"));
			break;
		case RIJNDAEL_UNSUPPORTED_DIRECTION:
			setLastError(__tr2qs("Unsupported direction"));
			break;
		case RIJNDAEL_UNSUPPORTED_KEY_LENGTH:
			setLastError(__tr2qs("Unsupported key length"));
			break;
		case RIJNDAEL_BAD_KEY:
			setLastError(__tr2qs("Bad key data"));
			break;
		case RIJNDAEL_NOT_INITIALIZED:
			setLastError(__tr2qs("Engine not initialized"));
			break;
		case RIJNDAEL_BAD_DIRECTION:
			setLastError(__tr2qs("Invalid direction for this engine"));
			break;
		case RIJNDAEL_CORRUPTED_DATA:
			setLastError(__tr2qs("Corrupted message data or invalid decryption key"));
			break;
		default:
			setLastError(__tr2qs("Unknown error"));
			break;
	}
}

KviCryptEngine::EncryptResult KviRijndaelEngine::encrypt(const char * plainText, KviCString & outBuffer)
{
	if(!m_pEncryptCipher)
	{
		setLastError(__tr2qs("Oops! Encryption cipher not initialized"));
		return KviCryptEngine::EncryptError;
	}
	int len = (int)kvi_strLen(plainText);
	char * buf = (char *)KviMemory::allocate(len + 16); // needed for the eventual padding
	unsigned char * iv = nullptr;
	if(m_bEncryptMode == CBC)
	{
		iv = (unsigned char *)KviMemory::allocate(MAX_IV_SIZE);
		InitVectorEngine::fillRandomIV(iv, MAX_IV_SIZE);
	}

	int retVal = m_pEncryptCipher->padEncrypt((const unsigned char *)plainText, len, (unsigned char *)buf, iv);
	if(retVal < 0)
	{
		if(m_bEncryptMode == CBC)
			KviMemory::free(iv);
		KviMemory::free(buf);
		setLastErrorFromRijndaelErrorCode(retVal);
		return KviCryptEngine::EncryptError;
	}

	if(m_bEncryptMode == CBC)
	{
		// prepend the iv to the cyphered text
		buf = (char *)KviMemory::reallocate(buf, retVal + MAX_IV_SIZE);
		KviMemory::move(buf + MAX_IV_SIZE, buf, retVal);
		KviMemory::move(buf, iv, MAX_IV_SIZE);
		KviMemory::free(iv);
		retVal += MAX_IV_SIZE;
	}

	if(!binaryToAscii(buf, retVal, outBuffer))
	{
		KviMemory::free(buf);
		return KviCryptEngine::EncryptError;
	}
	KviMemory::free(buf);

	if(outBuffer.len() > maxEncryptLen())
	{
		if(maxEncryptLen() > 0)
		{
			setLastError(__tr2qs("Data buffer too long"));
			return KviCryptEngine::EncryptError;
		}
	}
	outBuffer.prepend((char) KviControlCodes::CryptEscape);
	return KviCryptEngine::Encrypted;
}

KviCryptEngine::DecryptResult KviRijndaelEngine::decrypt(const char * inBuffer, KviCString & plainText)
{
	if(!m_pDecryptCipher)
	{
		setLastError(__tr2qs("Oops! Decryption cipher not initialized"));
		return KviCryptEngine::DecryptError;
	}

	if(*inBuffer != KviControlCodes::CryptEscape)
	{
		plainText = inBuffer;
		return KviCryptEngine::DecryptOkWasPlainText;
	}

	inBuffer++;

	if(!*inBuffer)
	{
		plainText = inBuffer;
		return KviCryptEngine::DecryptOkWasPlainText; // empty buffer
	}

	int len;
	char * binary;

	if(!asciiToBinary(inBuffer, &len, &binary))
		return KviCryptEngine::DecryptError;

	char * buf = (char *)KviMemory::allocate(len + 1);
	unsigned char * iv = nullptr;
	if(m_bEncryptMode == CBC)
	{
		// extract the IV from the cyphered string
		len -= MAX_IV_SIZE;
		iv = (unsigned char *)KviMemory::allocate(MAX_IV_SIZE);
		KviMemory::move(iv, binary, MAX_IV_SIZE);
		KviMemory::move(binary, binary + MAX_IV_SIZE, len);
		binary = (char *)KviMemory::reallocate(binary, len);
	}

	int retVal = m_pDecryptCipher->padDecrypt((const unsigned char *)binary, len, (unsigned char *)buf, iv);
	KviMemory::free(binary);
	KviMemory::free(iv);

	if(retVal < 0)
	{
		KviMemory::free(buf);
		setLastErrorFromRijndaelErrorCode(retVal);
		return KviCryptEngine::DecryptError;
	}

	buf[retVal] = '\0';

	plainText = buf;

	KviMemory::free(buf);
	return KviCryptEngine::DecryptOkWasEncrypted;
}

bool KviRijndaelHexEngine::binaryToAscii(const char * inBuffer, int len, KviCString & outBuffer)
{
	outBuffer.bufferToHex(inBuffer, len);
	return true;
}

bool KviRijndaelHexEngine::asciiToBinary(const char * inBuffer, int * len, char ** outBuffer)
{
	KviCString hex(inBuffer);
	char * tmpBuf;
	*len = hex.hexToBuffer(&tmpBuf, false);
	if(*len < 0)
	{
		setLastError(__tr2qs("The message is not a hexadecimal string: this is not my stuff"));
		return false;
	}
	else
	{
		if(*len > 0)
		{
			*outBuffer = (char *)KviMemory::allocate(*len);
			KviMemory::move(*outBuffer, tmpBuf, *len);
			KviCString::freeBuffer(tmpBuf);
		}
	}
	return true;
}

bool KviRijndaelBase64Engine::binaryToAscii(const char * inBuffer, int len, KviCString & outBuffer)
{
	outBuffer.bufferToBase64(inBuffer, len);
	return true;
}

bool KviRijndaelBase64Engine::asciiToBinary(const char * inBuffer, int * len, char ** outBuffer)
{
	KviCString base64(inBuffer);
	char * tmpBuf;
	*len = base64.base64ToBuffer(&tmpBuf, false);
	if(*len < 0)
	{
		setLastError(__tr2qs("The message is not a base64 string: this is not my stuff"));
		return false;
	}
	else
	{
		if(*len > 0)
		{
			*outBuffer = (char *)KviMemory::allocate(*len);
			KviMemory::move(*outBuffer, tmpBuf, *len);
			KviCString::freeBuffer(tmpBuf);
		}
	}
	return true;
}

static KviCryptEngine * allocRijndael128HexEngine()
{
	return new KviRijndael128HexEngine();
}

static KviCryptEngine * allocRijndael192HexEngine()
{
	return new KviRijndael192HexEngine();
}

static KviCryptEngine * allocRijndael256HexEngine()
{
	return new KviRijndael256HexEngine();
}

static KviCryptEngine * allocRijndael128Base64Engine()
{
	return new KviRijndael128Base64Engine();
}

static KviCryptEngine * allocRijndael192Base64Engine()
{
	return new KviRijndael192Base64Engine();
}

static KviCryptEngine * allocRijndael256Base64Engine()
{
	return new KviRijndael256Base64Engine();
}

static void deallocRijndaelCryptEngine(KviCryptEngine * e)
{
	delete e;
}

// Mircryption stuff

#include "BlowFish.h"

KviMircryptionEngine::KviMircryptionEngine()
    : KviCryptEngine()
{
	g_pEngineList->append(this);
}

KviMircryptionEngine::~KviMircryptionEngine()
{
	g_pEngineList->removeRef(this);
}

bool KviMircryptionEngine::init(const char * encKey, int encKeyLen, const char * decKey, int decKeyLen)
{
	if(encKey && (encKeyLen > 0))
	{
		if(!(decKey && (decKeyLen > 0)))
		{
			decKey = encKey;
			decKeyLen = encKeyLen;
		} // else all
	}
	else
	{
		// no encrypt key specified...
		if(decKey && decKeyLen)
		{
			encKey = decKey;
			encKeyLen = decKeyLen;
		}
		else
		{
			// both keys missing
			setLastError(__tr2qs("Missing both encryption and decryption key: at least one is needed"));
			return false;
		}
	}
	m_szEncryptKey = KviCString(encKey, encKeyLen);
	m_szDecryptKey = KviCString(decKey, decKeyLen);

	m_bEncryptCBC = true;
	m_bDecryptCBC = true;

	if((kvi_strEqualCIN("ecb:", m_szEncryptKey.ptr(), 4) || kvi_strEqualCIN("old:", m_szEncryptKey.ptr(), 4))
	    && (m_szEncryptKey.len() > 4))
	{
		m_bEncryptCBC = false;
		m_szEncryptKey.cutLeft(4);
	}
	else if(kvi_strEqualCIN("cbc:", m_szEncryptKey.ptr(), 4) && (m_szEncryptKey.len() > 4))
	{
		m_szEncryptKey.cutLeft(4);
	}

	if((kvi_strEqualCIN("ecb:", m_szDecryptKey.ptr(), 4) || kvi_strEqualCIN("old:", m_szDecryptKey.ptr(), 4))
	    && (m_szDecryptKey.len() > 4))
	{
		m_bDecryptCBC = false;
		m_szDecryptKey.cutLeft(4);
	}
	else if(kvi_strEqualCIN("cbc:", m_szDecryptKey.ptr(), 4) && (m_szDecryptKey.len() > 4))
	{
		m_szDecryptKey.cutLeft(4);
	}

	return true;
}

KviCryptEngine::EncryptResult KviMircryptionEngine::encrypt(const char * plainText, KviCString & outBuffer)
{
	KviCString szPlain = plainText;
	outBuffer = "";
	if(m_bEncryptCBC)
	{
		if(!doEncryptCBC(szPlain, outBuffer))
			return KviCryptEngine::EncryptError;
	}
	else
	{
		if(!doEncryptECB(szPlain, outBuffer))
			return KviCryptEngine::EncryptError;
	}
	outBuffer.prepend("+OK ");

	if(outBuffer.len() > maxEncryptLen())
	{
		if(maxEncryptLen() > 0)
		{
			setLastError(__tr2qs("Data buffer too long"));
			return KviCryptEngine::EncryptError;
		}
	}

	//outBuffer = MCPS2_STARTTAG;
	//outBuffer += MCPS2_ENDTAG;
	return KviCryptEngine::Encrypted;
}

KviCryptEngine::DecryptResult KviMircryptionEngine::decrypt(const char * inBuffer, KviCString & plainText)
{
	plainText = "";
	KviCString szIn = inBuffer;
	// various old versions
	if(kvi_strEqualCSN(inBuffer, "mcps ", 5))
		szIn.cutLeft(5);
	else if(kvi_strEqualCSN(inBuffer, "+OK ", 4))
		szIn.cutLeft(4);
	else if(kvi_strEqualCSN(inBuffer, "OK ", 3)) // some servers strip out the +
		szIn.cutLeft(3);
	else
	{
		plainText = szIn;
		return KviCryptEngine::DecryptOkWasPlainText;
	}

	if(m_bDecryptCBC)
		return doDecryptCBC(szIn, plainText) ? KviCryptEngine::DecryptOkWasEncrypted : KviCryptEngine::DecryptError;
	return doDecryptECB(szIn, plainText) ? KviCryptEngine::DecryptOkWasEncrypted : KviCryptEngine::DecryptError;
}

bool KviMircryptionEngine::doEncryptECB(KviCString & plain, KviCString & encoded)
{
	// make sure it is a multiple of 8 bytes (eventually pad with zeroes)
	if(plain.len() % 8)
	{
		int oldL = plain.len();
		plain.setLen(plain.len() + (8 - (plain.len() % 8)));
		char * padB = plain.ptr() + oldL;
		char * padE = plain.ptr() + plain.len();
		while(padB < padE)
			*padB++ = 0;
	}

	unsigned char * out = (unsigned char *)KviMemory::allocate(plain.len()); // we use this to avoid endiannes problems

	BlowFish bf((unsigned char *)m_szEncryptKey.ptr(), m_szEncryptKey.len());
	bf.ResetChain();
	bf.Encrypt((unsigned char *)plain.ptr(), out, plain.len(), BlowFish::ECB);

	UglyBase64::encode(out, plain.len(), encoded);
	KviMemory::free(out);
	return true;
}

bool KviMircryptionEngine::doDecryptECB(KviCString & encoded, KviCString & plain)
{
	unsigned char * buf = nullptr;
	int len;
	UglyBase64::decode(encoded, &buf, &len);

	plain.setLen(len);
	BlowFish bf((unsigned char *)m_szDecryptKey.ptr(), m_szDecryptKey.len());
	bf.ResetChain();
	bf.Decrypt(buf, (unsigned char *)plain.ptr(), len, BlowFish::ECB);

	KviMemory::free(buf);

	return true;
}

bool KviMircryptionEngine::doEncryptCBC(KviCString & plain, KviCString & encoded)
{
	// make sure it is a multiple of 8 bytes (eventually pad with zeroes)
	if(plain.len() % 8)
	{
		int oldL = plain.len();
		plain.setLen(plain.len() + (8 - (plain.len() % 8)));
		char * padB = plain.ptr() + oldL;
		char * padE = plain.ptr() + plain.len();
		while(padB < padE)
			*padB++ = 0;
	}

	int ll = plain.len() + 8;
	unsigned char * in = (unsigned char *)KviMemory::allocate(ll);

	InitVectorEngine::fillRandomIV(in, 8);

	KviMemory::copy(in + 8, plain.ptr(), plain.len());

	// encrypt
	unsigned char * out = (unsigned char *)KviMemory::allocate(ll);
	BlowFish bf((unsigned char *)m_szEncryptKey.ptr(), m_szEncryptKey.len());
	bf.ResetChain();
	bf.Encrypt(in, out, ll, BlowFish::CBC);
	KviMemory::free(in);

	encoded.bufferToBase64((const char *)out, ll);
	KviMemory::free(out);

	encoded.prepend('*'); // prepend the signature

	return true;
}

bool KviMircryptionEngine::doDecryptCBC(KviCString & encoded, KviCString & plain)
{
	if(*(encoded.ptr()) != '*')
	{
		qDebug("WARNING: specified a CBC key but the incoming message doesn't seem to be a CBC one");
		return doDecryptECB(encoded, plain);
	}
	encoded.cutLeft(1);

	char * tmpBuf;
	int len = encoded.base64ToBuffer(&tmpBuf, false);
	if(len < 0)
	{
		setLastError(__tr2qs("The message is not a base64 string: this is not my stuff"));
		return false;
	}
	if((len < 8) || (len % 8))
	{
		setLastError(__tr2qs("The message doesn't seem to be encoded with CBC Mircryption"));
		if(len > 0)
			KviCString::freeBuffer(tmpBuf);
		return false;
	}

	plain.setLen(len);
	BlowFish bf((unsigned char *)m_szDecryptKey.ptr(), m_szDecryptKey.len());
	bf.ResetChain();
	bf.Decrypt((unsigned char *)tmpBuf, (unsigned char *)plain.ptr(), len, BlowFish::CBC);

	// kill the first 8 bytes (random IV)
	plain.cutLeft(8);

	KviCString::freeBuffer(tmpBuf);

	return true;
}

static KviCryptEngine * allocMircryptionEngine()
{
	return new KviMircryptionEngine();
}

#endif

///////////////////////////////////////////////////////////////////////////////
// module routines
///////////////////////////////////////////////////////////////////////////////

static bool rijndael_module_init(KviModule * m)
{
#ifdef COMPILE_CRYPT_SUPPORT
	g_pEngineList = new KviPointerList<KviCryptEngine>;
	g_pEngineList->setAutoDelete(false);

	QString szFormat = __tr2qs("Cryptographic engine based on the Advanced Encryption Standard (AES) algorithm called Rijndael. "
	                           "<br/>The text is first encrypted with Rijndael and then converted to %1 notation. "
	                           "The keys used are %2 bit long and will be padded with zeros if you provide shorter ones. "
	                           "If only one key is provided, this engine will use it for both encrypting and decrypting. "
	                           "See the Rijndael module documentation for more info on the algorithm used. "
	                           "<br/>This engine works in CBC mode by default: other modes are considered INSECURE and should be avoided. "
	                           "The old pseudo-CBC mode used in KVIrc &lt; 4.2 is still available prefixing your key(s) with \"old:\"; "
	                           "if you want to use ECB mode you must prefix your key(s) with \"ecb:\".");

	// FIXME: Maybe convert this repeated code to a function eh ?

	KviCryptEngineDescription * d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael128Hex";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("hexadecimal")).arg(128);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael128HexEngine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael192Hex";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("hexadecimal")).arg(192);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael192HexEngine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael256Hex";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("hexadecimal")).arg(256);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael256HexEngine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael128Base64";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("base64")).arg(128);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael128Base64Engine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael192Base64";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("base64")).arg(192);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael192Base64Engine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Rijndael256Base64";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = QString(szFormat).arg(__tr2qs("base64")).arg(256);
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocRijndael256Base64Engine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	d = new KviCryptEngineDescription;
	d->m_szName = "Mircryption";
	d->m_szAuthor = "Szymon Stefanek";
	d->m_szDescription = __tr2qs("Popular cryptographic engine based on the Blowfish encryption algorithm. "
	                             "<br/>The text is first encrypted with Blowfish and then converted to base64 notation. "
	                             "The keys used have variable length and are specified as character strings. "
	                             "You can specify keys with length up to 56 bytes (448 bits) by default or change this with /option uintMaximumBlowFishKeySize UINT. "
	                             "Blowfish allows for up to 72 bytes for keys, but it is not advised to use more than 56 bytes for security reasons. "
	                             "Only increase this value if you need compatibility with another client's Blowfish implementation. "
	                             "If only one key is provided, this engine will use it for both encrypting and decrypting. "
	                             "<br/>This engine works in CBC mode by default: if you want to use the old and INSECURE ECB mode you must prefix your key(s) with \"ecb:\" or \"old:\".");
	d->m_iFlags = KviCryptEngine::CanEncrypt | KviCryptEngine::CanDecrypt | KviCryptEngine::WantEncryptKey | KviCryptEngine::WantDecryptKey;
	d->m_allocFunc = allocMircryptionEngine;
	d->m_deallocFunc = deallocRijndaelCryptEngine;
	m->registerCryptEngine(d);

	return true;
#else
	return false;
#endif
}

static bool rijndael_module_cleanup(KviModule * m)
{
#ifdef COMPILE_CRYPT_SUPPORT
	while(g_pEngineList->first())
		delete g_pEngineList->first();
	delete g_pEngineList;
	g_pEngineList = nullptr;
	m->unregisterCryptEngines();
	return true;
#else
	return false;
#endif
}

static bool rijndael_module_can_unload(KviModule *)
{
#ifdef COMPILE_CRYPT_SUPPORT
	return g_pEngineList->isEmpty();
#else
	return true;
#endif
}

KVIRC_MODULE(
    "Rijndael crypt engine",
    "4.0.0",
    "Szymon Stefanek <pragma at kvirc dot net>\n"
    "Fabio Bas <ctrlaltca at gmail dot com>",
    "Exports the rijndael crypt engine",
    rijndael_module_init,
    rijndael_module_can_unload,
    0,
    rijndael_module_cleanup,
    0)