-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathqaesencryption.cpp
More file actions
858 lines (777 loc) · 30.3 KB
/
qaesencryption.cpp
File metadata and controls
858 lines (777 loc) · 30.3 KB
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
#include "qaesencryption.h"
#include <QDebug>
#include <cstddef>
#ifdef USE_INTEL_AES_IF_AVAILABLE
#include "aesni/aesni-key-exp.h"
#include "aesni/aesni-key-init.h"
#include "aesni/aesni-enc-ecb.h"
#include "aesni/aesni-enc-cbc.h"
#include "aesni/aesni-enc-cfb.h"
#include "aesni/aesni-enc-ofb.h"
#include "aesni/aesni-enc-ctr.h"
#endif
namespace {
// Zeroes key material in a QByteArray before it goes out of scope.
// A volatile pointer is used to prevent the compiler from eliding the write
// as a "dead store" — a risk with plain memset when the buffer is not read
// again afterwards. This is best-effort: the C++ standard does not formally
// guarantee volatile writes survive every optimisation pass, but all major
// compilers (GCC, Clang, MSVC) respect them in practice.
void secureZero(QByteArray &ba)
{
if (ba.isEmpty())
return;
volatile char *p = ba.data();
for (int i = 0; i < ba.size(); ++i)
p[i] = 0;
}
#ifdef USE_INTEL_AES_IF_AVAILABLE
void secureZero(void *ptr, std::size_t len)
{
volatile unsigned char *p = static_cast<volatile unsigned char *>(ptr);
for (std::size_t i = 0; i < len; ++i)
p[i] = 0;
}
#endif
quint8 xTime(quint8 x)
{
return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
quint8 multiply(quint8 x, quint8 y)
{
return (((y & 1) * x) ^ ((y>>1 & 1) * xTime(x)) ^ ((y>>2 & 1) * xTime(xTime(x))) ^ ((y>>3 & 1)
* xTime(xTime(xTime(x)))) ^ ((y>>4 & 1) * xTime(xTime(xTime(xTime(x))))));
}
} // namespace
/*
* Static Functions
* */
QByteArray QAESEncryption::Crypt(QAESEncryption::Aes level, QAESEncryption::Mode mode, const QByteArray &rawText,
const QByteArray &key, const QByteArray &iv, QAESEncryption::Padding padding,
bool *ok)
{
return QAESEncryption(level, mode, padding).encode(rawText, key, iv, ok);
}
QByteArray QAESEncryption::Decrypt(QAESEncryption::Aes level, QAESEncryption::Mode mode, const QByteArray &rawText,
const QByteArray &key, const QByteArray &iv, QAESEncryption::Padding padding,
bool *ok)
{
return QAESEncryption(level, mode, padding).decode(rawText, key, iv, ok);
}
QByteArray QAESEncryption::ExpandKey(QAESEncryption::Aes level, QAESEncryption::Mode mode, const QByteArray &key, bool isEncryptionKey)
{
return QAESEncryption(level, mode).expandKey(key, isEncryptionKey);
}
QByteArray QAESEncryption::RemovePadding(const QByteArray &rawText, QAESEncryption::Padding padding, bool *ok)
{
if (ok) *ok = false;
if (rawText.isEmpty()) {
if (ok) *ok = true;
return rawText;
}
QByteArray ret(rawText);
switch (padding)
{
case Padding::ZERO:
//Works only if the last byte of the decoded array is not zero
while (ret.at(ret.length()-1) == 0x00)
ret.remove(ret.length()-1, 1);
break;
case Padding::PKCS7:
{
// PKCS7 requires every padding byte to equal the padding length.
// Validate before removing — silently stripping arbitrary bytes is a
// security issue (enables padding oracle and data corruption attacks).
//
// Constant-time validation: the loop always inspects every byte in the
// last block regardless of whether an invalid byte is found early.
// An early return would create a measurable timing difference that an
// attacker could exploit via a padding oracle (Vaudenay 2002).
const int len = ret.size();
const quint8 padLen = static_cast<quint8>(ret.at(len - 1));
quint8 good = static_cast<quint8>((padLen >= 1) & (padLen <= 16) & (padLen <= len));
for (int i = 0; i < 16 && i < len; ++i) {
// Check byte at position (len - 1 - i). It must equal padLen
// if it falls within the padding region (i < padLen).
const quint8 b = static_cast<quint8>(ret.at(len - 1 - i));
// inPad is 1 when this byte is in the padding region, 0 otherwise.
// The comparison uses unsigned arithmetic to avoid branches.
const quint8 inPad = static_cast<quint8>(static_cast<quint8>(i) < padLen);
// mismatch is non-zero when the byte differs from padLen.
const quint8 mismatch = static_cast<quint8>(b ^ padLen);
// Clear 'good' if a padding byte doesn't match (branchless).
good &= static_cast<quint8>(~(inPad & static_cast<quint8>(mismatch != 0)));
}
if (good & 1) {
ret.remove(len - padLen, padLen);
} else {
qWarning("QAESEncryption::RemovePadding: invalid PKCS7 padding — buffer returned unchanged");
return ret; // ok remains false
}
break;
}
case Padding::ISO:
{
// Find the last byte which is not zero
int marker_index = ret.length() - 1;
for (; marker_index >= 0; --marker_index)
{
if (ret.at(marker_index) != 0x00)
{
break;
}
}
// And check if it's the byte for marking padding
if (ret.at(marker_index) == '\x80')
{
ret.truncate(marker_index);
}
break;
}
default:
//do nothing
break;
}
if (ok) *ok = true;
return ret;
}
QByteArray QAESEncryption::generateKey(const QByteArray &password, const QByteArray &salt,
QAESEncryption::Aes level,
QCryptographicHash::Algorithm algo, int iterations)
{
// Cap iterations to prevent callers from causing an indefinite hang;
// 500k is well above any practical default while blocking runaway values.
if (password.isEmpty() || salt.isEmpty() || iterations < 1 || iterations > 500000)
return QByteArray();
int keyLen = 0;
switch (level) {
case AES_128: keyLen = 16; break;
case AES_192: keyLen = 24; break;
case AES_256: keyLen = 32; break;
default: return QByteArray();
}
// PBKDF2 per RFC 2898 §5.2, PRF = HMAC-<algo>
// quint32 matches the RFC's 4-byte unsigned block counter, avoiding signed overflow.
QByteArray derived;
for (quint32 block = 1; derived.size() < keyLen; ++block) {
// U1 = HMAC(password, salt || INT(block))
QByteArray blockBytes(4, 0);
blockBytes[0] = static_cast<char>((block >> 24) & 0xff);
blockBytes[1] = static_cast<char>((block >> 16) & 0xff);
blockBytes[2] = static_cast<char>((block >> 8) & 0xff);
blockBytes[3] = static_cast<char>( block & 0xff);
QMessageAuthenticationCode hmac(algo, password);
hmac.addData(salt);
hmac.addData(blockBytes);
QByteArray u = hmac.result();
QByteArray xorSum = u;
for (int i = 1; i < iterations; ++i) {
QMessageAuthenticationCode hmacI(algo, password);
hmacI.addData(u);
u = hmacI.result();
for (int j = 0; j < xorSum.size(); ++j)
xorSum[j] = static_cast<char>(static_cast<quint8>(xorSum[j]) ^ static_cast<quint8>(u[j]));
}
derived.append(xorSum);
// QByteArray does not zero memory on destruction, so key material would
// otherwise linger on the heap. Securely zero before leaving scope.
secureZero(u);
secureZero(xorSum);
}
QByteArray result = derived.left(keyLen);
secureZero(derived);
return result;
}
/*
* End Static function declarations
* */
/*
* End Local functions
* */
namespace {
struct AesParams { int nk, keylen, nr, expandedKey, userKeySize; };
static const AesParams kAesParams[] = {
{4, 16, 10, 176, 128}, // AES_128
{6, 24, 12, 208, 192}, // AES_192
{8, 32, 14, 240, 256}, // AES_256
};
inline const AesParams& aesParams(int level) {
return kAesParams[(level >= 0 && level <= 2) ? level : 0];
}
} // namespace
QAESEncryption::QAESEncryption(Aes level, Mode mode,
Padding padding)
: m_nb(4), m_blocklen(16), m_level(level), m_mode(mode), m_padding(padding)
, m_aesNIAvailable(false)
{
#ifdef USE_INTEL_AES_IF_AVAILABLE
m_aesNIAvailable = check_aesni_support();
#endif
const AesParams& p = aesParams(level);
m_nk = p.nk;
m_keyLen = p.keylen;
m_nr = p.nr;
m_expandedKey = p.expandedKey;
}
QByteArray QAESEncryption::getPadding(int currSize, int alignment)
{
int size = (alignment - currSize % alignment) % alignment;
switch(m_padding)
{
case Padding::ZERO:
return QByteArray(size, 0x00);
break;
case Padding::PKCS7:
if (size == 0)
size = alignment;
return QByteArray(size, size);
break;
case Padding::ISO:
if (size > 0)
return QByteArray (size - 1, 0x00).prepend('\x80');
break;
case Padding::NONE:
return QByteArray();
default:
return QByteArray(size, 0x00);
break;
}
return QByteArray();
}
QByteArray QAESEncryption::expandKey(const QByteArray &key, bool isEncryptionKey)
{
// isEncryptionKey is only used by the AES-NI path; suppress the warning
// in software-only builds without removing the parameter from the public API.
Q_UNUSED(isEncryptionKey)
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
const AesParams& p = aesParams(m_level);
AES_KEY aesKey;
if (isEncryptionKey)
AES_set_encrypt_key((unsigned char*) key.constData(), p.userKeySize, &aesKey);
else
AES_set_decrypt_key((unsigned char*) key.constData(), p.userKeySize, &aesKey);
QByteArray expKey(p.expandedKey, 0);
memcpy(expKey.data(), (char*) aesKey.KEY, p.expandedKey);
secureZero(aesKey.KEY, p.expandedKey);
return expKey;
} else
#endif
{
int i, k;
quint8 tempa[4]; // Used for the column/row operations
QByteArray roundKey(key); // The first round key is the key itself.
roundKey.resize(m_expandedKey); // Pre-allocate to final size to avoid O(n²) insert shifts.
// All other round keys are found from the previous round keys.
//i == Nk
for(i = m_nk; i < m_nb * (m_nr + 1); i++)
{
tempa[0] = static_cast<quint8>(roundKey.at((i-1) * 4 + 0));
tempa[1] = static_cast<quint8>(roundKey.at((i-1) * 4 + 1));
tempa[2] = static_cast<quint8>(roundKey.at((i-1) * 4 + 2));
tempa[3] = static_cast<quint8>(roundKey.at((i-1) * 4 + 3));
if (i % m_nk == 0)
{
// This function shifts the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
k = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = k;
// Function Subword()
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
tempa[0] = tempa[0] ^ Rcon[i/m_nk];
}
if (m_level == AES_256 && i % m_nk == 4)
{
// Function Subword()
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
roundKey[i * 4 + 0] = static_cast<quint8>(roundKey.at((i - m_nk) * 4 + 0)) ^ tempa[0];
roundKey[i * 4 + 1] = static_cast<quint8>(roundKey.at((i - m_nk) * 4 + 1)) ^ tempa[1];
roundKey[i * 4 + 2] = static_cast<quint8>(roundKey.at((i - m_nk) * 4 + 2)) ^ tempa[2];
roundKey[i * 4 + 3] = static_cast<quint8>(roundKey.at((i - m_nk) * 4 + 3)) ^ tempa[3];
}
return roundKey;
}
}
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
void QAESEncryption::addRoundKey(QByteArray &state, const quint8 round, const QByteArray &expKey)
{
QByteArray::iterator it = state.begin();
for(int i=0; i < 16; ++i)
it[i] = static_cast<quint8>(it[i]) ^ static_cast<quint8>(expKey.at(round * m_nb * 4 + (i/4) * m_nb + (i%4)));
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void QAESEncryption::subBytes(QByteArray &state)
{
QByteArray::iterator it = state.begin();
for(int i = 0; i < 16; i++)
it[i] = getSBoxValue(static_cast<quint8>(it[i]));
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
void QAESEncryption::shiftRows(QByteArray &state)
{
QByteArray::iterator it = state.begin();
quint8 temp;
//Keep in mind that QByteArray is column-driven!!
//Shift 1 to left
temp = static_cast<quint8>(it[1]);
it[1] = static_cast<quint8>(it[5]);
it[5] = static_cast<quint8>(it[9]);
it[9] = static_cast<quint8>(it[13]);
it[13] = static_cast<quint8>(temp);
//Shift 2 to left
temp = static_cast<quint8>(it[2]);
it[2] = static_cast<quint8>(it[10]);
it[10] = static_cast<quint8>(temp);
temp = static_cast<quint8>(it[6]);
it[6] = static_cast<quint8>(it[14]);
it[14] = static_cast<quint8>(temp);
//Shift 3 to left
temp = static_cast<quint8>(it[3]);
it[3] = static_cast<quint8>(it[15]);
it[15] = static_cast<quint8>(it[11]);
it[11] = static_cast<quint8>(it[7]);
it[7] = static_cast<quint8>(temp);
}
// MixColumns function mixes the columns of the state matrix
//optimized!!
void QAESEncryption::mixColumns(QByteArray &state)
{
QByteArray::iterator it = state.begin();
quint8 tmp, tm, t;
for(int i = 0; i < 16; i += 4){
t = static_cast<quint8>(it[i]);
tmp = static_cast<quint8>(it[i]) ^ static_cast<quint8>(it[i+1]) ^ static_cast<quint8>(it[i+2]) ^ static_cast<quint8>(it[i+3]) ;
tm = xTime( static_cast<quint8>(it[i]) ^ static_cast<quint8>(it[i+1]) );
it[i] = static_cast<quint8>(it[i]) ^ static_cast<quint8>(tm) ^ static_cast<quint8>(tmp);
tm = xTime( static_cast<quint8>(it[i+1]) ^ static_cast<quint8>(it[i+2]));
it[i+1] = static_cast<quint8>(it[i+1]) ^ static_cast<quint8>(tm) ^ static_cast<quint8>(tmp);
tm = xTime( static_cast<quint8>(it[i+2]) ^ static_cast<quint8>(it[i+3]));
it[i+2] =static_cast<quint8>(it[i+2]) ^ static_cast<quint8>(tm) ^ static_cast<quint8>(tmp);
tm = xTime(static_cast<quint8>(it[i+3]) ^ static_cast<quint8>(t));
it[i+3] =static_cast<quint8>(it[i+3]) ^ static_cast<quint8>(tm) ^ static_cast<quint8>(tmp);
}
}
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
void QAESEncryption::invMixColumns(QByteArray &state)
{
QByteArray::iterator it = state.begin();
quint8 a,b,c,d;
for(int i = 0; i < 16; i+=4){
a = static_cast<quint8>(it[i]);
b = static_cast<quint8>(it[i+1]);
c = static_cast<quint8>(it[i+2]);
d = static_cast<quint8>(it[i+3]);
it[i] = static_cast<quint8>(multiply(a, 0x0e) ^ multiply(b, 0x0b) ^ multiply(c, 0x0d) ^ multiply(d, 0x09));
it[i+1] = static_cast<quint8>(multiply(a, 0x09) ^ multiply(b, 0x0e) ^ multiply(c, 0x0b) ^ multiply(d, 0x0d));
it[i+2] = static_cast<quint8>(multiply(a, 0x0d) ^ multiply(b, 0x09) ^ multiply(c, 0x0e) ^ multiply(d, 0x0b));
it[i+3] = static_cast<quint8>(multiply(a, 0x0b) ^ multiply(b, 0x0d) ^ multiply(c, 0x09) ^ multiply(d, 0x0e));
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void QAESEncryption::invSubBytes(QByteArray &state)
{
QByteArray::iterator it = state.begin();
for(int i = 0; i < 16; ++i)
it[i] = getSBoxInvert(static_cast<quint8>(it[i]));
}
void QAESEncryption::invShiftRows(QByteArray &state)
{
QByteArray::iterator it = state.begin();
quint8 temp;
//Keep in mind that QByteArray is column-driven!!
//Shift 1 to right
temp = static_cast<quint8>(it[13]);
it[13] = static_cast<quint8>(it[9]);
it[9] = static_cast<quint8>(it[5]);
it[5] = static_cast<quint8>(it[1]);
it[1] = static_cast<quint8>(temp);
//Shift 2
temp = static_cast<quint8>(it[10]);
it[10] = static_cast<quint8>(it[2]);
it[2] = static_cast<quint8>(temp);
temp = static_cast<quint8>(it[14]);
it[14] = static_cast<quint8>(it[6]);
it[6] = static_cast<quint8>(temp);
//Shift 3
temp = static_cast<quint8>(it[7]);
it[7] = static_cast<quint8>(it[11]);
it[11] = static_cast<quint8>(it[15]);
it[15] = static_cast<quint8>(it[3]);
it[3] = static_cast<quint8>(temp);
}
QByteArray QAESEncryption::byteXor(const QByteArray &a, const QByteArray &b)
{
const int n = std::min(a.size(), b.size());
QByteArray ret(n, 0);
for (int i = 0; i < n; i++)
ret[i] = static_cast<quint8>(a[i]) ^ static_cast<quint8>(b[i]);
return ret;
}
// Cipher is the main function that encrypts the PlainText.
QByteArray QAESEncryption::cipher(const QByteArray &expKey, const QByteArray &in)
{
// State is kept entirely on the stack — no shared mutable member, making
// concurrent calls on the same instance safe.
QByteArray state(in);
// Add the First round key to the state before starting the rounds.
addRoundKey(state, 0, expKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for(quint8 round = 1; round < m_nr; ++round){
subBytes(state);
shiftRows(state);
mixColumns(state);
addRoundKey(state, round, expKey);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
subBytes(state);
shiftRows(state);
addRoundKey(state, m_nr, expKey);
return state;
}
QByteArray QAESEncryption::invCipher(const QByteArray &expKey, const QByteArray &in)
{
// State is kept entirely on the stack — no shared mutable member, making
// concurrent calls on the same instance safe.
QByteArray state(in);
// Add the First round key to the state before starting the rounds.
addRoundKey(state, m_nr, expKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for(quint8 round=m_nr-1; round>0 ; round--){
invShiftRows(state);
invSubBytes(state);
addRoundKey(state, round, expKey);
invMixColumns(state);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
invShiftRows(state);
invSubBytes(state);
addRoundKey(state, 0, expKey);
return state;
}
// OFB and CTR are symmetric (encrypt == decrypt). A single implementation
// is shared by encode() and decode() to avoid duplication and divergence.
QByteArray QAESEncryption::xcryptOFB(const QByteArray &input, const QByteArray &expandedKey, const QByteArray &iv)
{
QByteArray ofbTemp;
ofbTemp.append(cipher(expandedKey, iv));
for (int i = m_blocklen; i < input.size(); i += m_blocklen)
ofbTemp.append(cipher(expandedKey, ofbTemp.right(m_blocklen)));
return byteXor(input, ofbTemp);
}
QByteArray QAESEncryption::xcryptCTR(const QByteArray &input, const QByteArray &expandedKey, const QByteArray &iv)
{
QByteArray result;
QByteArray counterBlock(iv);
for (int i = 0; i < input.size(); i += m_blocklen) {
QByteArray keyStream = cipher(expandedKey, counterBlock);
int blockSize = qMin(m_blocklen, input.size() - i);
result.append(byteXor(input.mid(i, blockSize), keyStream.left(blockSize)));
// Increment counter as a 128-bit big-endian integer (byte[15] is least significant).
unsigned char *ctr = reinterpret_cast<unsigned char*>(counterBlock.data());
for (int j = m_blocklen - 1; j >= 0; --j) {
if (++ctr[j] != 0)
break;
}
}
return result;
}
QByteArray QAESEncryption::encode(const QByteArray &rawText, const QByteArray &key, const QByteArray &iv, bool *ok)
{
if (ok) *ok = false;
if ((m_mode >= CBC && (iv.isEmpty() || iv.size() != m_blocklen)) || key.size() != m_keyLen)
return QByteArray();
// NONE padding is only valid for stream cipher modes (CFB, OFB, CTR).
// ECB and CBC require block-aligned input; reject unaligned input early.
if (m_padding == Padding::NONE && (m_mode == ECB || m_mode == CBC)
&& rawText.size() % m_blocklen != 0) {
return QByteArray();
}
QByteArray expandedKey = expandKey(key, true);
QByteArray alignedText(rawText);
// CTR is a stream cipher — no padding required; all other modes need block alignment.
if (m_mode != CTR)
alignedText.append(getPadding(rawText.size(), m_blocklen));
QByteArray result;
switch(m_mode)
{
case ECB: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable){
result.resize(alignedText.size());
AES_ECB_encrypt((unsigned char*) alignedText.constData(),
(unsigned char*) result.data(),
alignedText.size(),
expandedKey.constData(),
m_nr);
break;
}
#endif
for(int i=0; i < alignedText.size(); i+= m_blocklen)
result.append(cipher(expandedKey, alignedText.mid(i, m_blocklen)));
}
break;
case CBC: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable){
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
result.resize(alignedText.size());
AES_CBC_encrypt((unsigned char*) alignedText.constData(),
(unsigned char*) result.data(),
ivec,
alignedText.size(),
expandedKey.constData(),
m_nr);
// Zero the stack copy of the IV — it contains chained block state
// that could theoretically be used to reconstruct plaintext blocks.
secureZero(ivec, sizeof(ivec));
break;
}
#endif
QByteArray ivTemp(iv);
for(int i=0; i < alignedText.size(); i+= m_blocklen) {
alignedText.replace(i, m_blocklen, byteXor(alignedText.mid(i, m_blocklen),ivTemp));
result.append(cipher(expandedKey, alignedText.mid(i, m_blocklen)));
ivTemp = result.mid(i, m_blocklen);
}
}
break;
case CFB: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
result.resize(alignedText.size());
AES_CFB_encrypt((unsigned char*) alignedText.constData(),
(unsigned char*) result.data(),
ivec,
alignedText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
// CFB encrypt: C[i] = AES_E(C[i-1]) XOR P[i], C[-1] = IV
QByteArray cfbFeedback(iv);
for (int i = 0; i < alignedText.size(); i += m_blocklen) {
QByteArray block = byteXor(alignedText.mid(i, m_blocklen), cipher(expandedKey, cfbFeedback));
result.append(block);
cfbFeedback = block;
}
}
break;
case OFB: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
result.resize(alignedText.size());
AES_OFB_xcrypt((unsigned char*) alignedText.constData(),
(unsigned char*) result.data(),
ivec,
alignedText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
result.append(xcryptOFB(alignedText, expandedKey, iv));
}
break;
case CTR: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
result.resize(alignedText.size());
AES_CTR_xcrypt((unsigned char*) alignedText.constData(),
(unsigned char*) result.data(),
ivec,
alignedText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
result.append(xcryptCTR(alignedText, expandedKey, iv));
}
break;
default: break;
}
// Securely zero the expanded key schedule before returning — it contains
// key-derived material and QByteArray does not zero on destruction.
secureZero(expandedKey);
if (ok) *ok = true;
return result;
}
QByteArray QAESEncryption::decode(const QByteArray &rawText, const QByteArray &key, const QByteArray &iv, bool *ok)
{
if (ok) *ok = false;
// Stream cipher modes with no padding allow arbitrary-length ciphertext.
const bool isStreamMode = (m_mode == CTR)
|| ((m_mode == CFB || m_mode == OFB) && m_padding == Padding::NONE);
// CTR/CFB(NONE)/OFB(NONE) ciphertext can be any length; all other modes must be block-aligned.
if ((m_mode >= CBC && (iv.isEmpty() || iv.size() != m_blocklen)) || key.size() != m_keyLen
|| (rawText.size() % m_blocklen != 0 && !isStreamMode))
return QByteArray();
QByteArray ret;
QByteArray expandedKey;
#ifdef USE_INTEL_AES_IF_AVAILABLE
if(m_aesNIAvailable && m_mode <= CBC){
expandedKey = expandKey(key, false);
}else{
expandedKey = expandKey(key, true);
}
#else
expandedKey = expandKey(key, true);
#endif
//false or true here is very important
//the expandedKeys aren't the same for !aes-ni! ENcryption and DEcryption (only CBC and EBC)
//but if you are !NOT! using aes-ni then the expandedKeys for encryption and decryption are the SAME!!!
switch(m_mode)
{
case ECB:
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable){
ret.resize(rawText.size());
AES_ECB_decrypt((unsigned char*) rawText.constData(),
(unsigned char*) ret.data(),
rawText.size(),
expandedKey.constData(),
m_nr);
break;
}
#endif
for(int i=0; i < rawText.size(); i+= m_blocklen)
ret.append(invCipher(expandedKey, rawText.mid(i, m_blocklen)));
break;
case CBC:
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable){
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
ret.resize(rawText.size());
AES_CBC_decrypt((unsigned char*) rawText.constData(),
(unsigned char*) ret.data(),
ivec,
rawText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
{
QByteArray ivTemp(iv);
for(int i=0; i < rawText.size(); i+= m_blocklen){
ret.append(invCipher(expandedKey, rawText.mid(i, m_blocklen)));
ret.replace(i, m_blocklen, byteXor(ret.mid(i, m_blocklen),ivTemp));
ivTemp = rawText.mid(i, m_blocklen);
}
}
break;
case CFB: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
ret.resize(rawText.size());
AES_CFB_decrypt((unsigned char*) rawText.constData(),
(unsigned char*) ret.data(),
ivec,
rawText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
// CFB decrypt: P[i] = AES_E(C[i-1]) XOR C[i], C[-1] = IV
// Note: CFB uses the FORWARD cipher (AES_E) for decryption, not invCipher.
QByteArray cfbFeedback(iv);
for (int i = 0; i < rawText.size(); i += m_blocklen) {
ret.append(byteXor(rawText.mid(i, m_blocklen), cipher(expandedKey, cfbFeedback)));
cfbFeedback = rawText.mid(i, m_blocklen); // feedback is ciphertext, not plaintext
}
}
break;
case OFB: {
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
ret.resize(rawText.size());
AES_OFB_xcrypt((unsigned char*) rawText.constData(),
(unsigned char*) ret.data(),
ivec,
rawText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
ret.append(xcryptOFB(rawText, expandedKey, iv));
}
break;
case CTR: {
// CTR decryption is identical to encryption — reuse the same keystream.
#ifdef USE_INTEL_AES_IF_AVAILABLE
if (m_aesNIAvailable) {
quint8 ivec[16];
memcpy(ivec, iv.constData(), sizeof(ivec));
ret.resize(rawText.size());
AES_CTR_xcrypt((unsigned char*) rawText.constData(),
(unsigned char*) ret.data(),
ivec,
rawText.size(),
expandedKey.constData(),
m_nr);
secureZero(ivec, sizeof(ivec));
break;
}
#endif
ret.append(xcryptCTR(rawText, expandedKey, iv));
}
break;
default:
//do nothing
break;
}
// Securely zero the expanded key schedule before returning — it contains
// key-derived material and QByteArray does not zero on destruction.
secureZero(expandedKey);
if (ok) *ok = true;
return ret;
}
QByteArray QAESEncryption::removePadding(const QByteArray &rawText, bool *ok)
{
return RemovePadding(rawText, (Padding) m_padding, ok);
}