-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmicro_aes.c
2349 lines (2064 loc) · 88.5 KB
/
micro_aes.c
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
==============================================================================
Name : micro_aes.c
Author : polfosol
Version : 10
Copyright : copyright © 2022 - polfosol
Description : ANSI-C compatible implementation of µAES ™ library.
==============================================================================
*/
#include "micro_aes.h"
/*----------------------------------------------------------------------------*\
Constants and MACROs
\*----------------------------------------------------------------------------*/
enum basic_constants
{
BLOCKSIZE = (128) / 8, /* Block length in AES is 'always' 128-bits */
KEYSIZE = AES_KEY_SIZE,
Nb = BLOCKSIZE / 4, /* number of columns comprising a AES state */
Nk = KEYSIZE / 4, /* number of 32 bit words in a key. */
ROUNDS = Nk + 6, /* number of rounds in AES Cipher. */
LAST = BLOCKSIZE - 1, /* index of last element (LSB) in a block. */
HB = BLOCKSIZE / 2, /* length of a half-block unit. */
SP = 17 /* length of data blocks in poly-1305 mode. */
};
#define IMPLEMENT(x) (x) > 0
#define INCREASE_SECURITY 0 /* see the comments at the bottom of header */
#define DISCARD_SUBROUTINES 0
#define SMALL_CIPHER 0
/** Lookup-tables are "static constant", so that they can be placed in read-only
* storage instead of RAM. They can be computed dynamically trading ROM for RAM.
* This may be useful in (embedded) bootloader applications, where ROM is often
* limited. Note that sbox[y] = x, if and only if rsbox[x] = y. For more details
* on dynamic sbox computation, see https://en.wikipedia.org/wiki/Rijndael_S-box
*/
static const char sbox[256] =
"c|w{\362ko\3050\01g+\376\327\253v\312\202\311}""\372YG\360\255\324\242\257"
"\234\244r\300\267\375\223&6\?\367\3144\245\345\361q\3301\25\4\307#\303\030"
"\226\5\232\a\22\200\342\353\'\262u\t\203,\32\33nZ\240R;\326\263)\343/\204S"
"\321\0\355 \374\261[j\313\2769JLX\317\320\357\252\373CM3\205E\371\02\177P<"
"\237\250Q\243@\217\222\2358\365\274\266\332!\20\377\363\322\315\f\023\354_"
"\227D\27\304\247~=d]\31s`\201O\334\"*\220\210F\356\270\24\336^\v\333\3402:"
"\nI\06$\\\302\323\254b\221\225\344y\347\3107m\215\325N\251lV\364\352ez\256"
"\b\272x%.\034\246\264\306\350\335t\37K\275\213\212p>\265fH\3\366\16a5W\271"
"\206\301\035\236\341\370\230\21i\331\216\224\233\036\207\351\316U(\337\214"
"\241\211\r\277\346BhA\231-\17\260T\273\26";
#if DECRYPTION
static const char rsbox[256] =
"R\tj\32506\2458\277@\243\236\201\363\327\373|\3439\202\233/\377\2074\216CD"
"\304\336\351\313T{\2242\246\302#=\356L\225\vB\372\303N\b.\241f(\331$\262v["
"\242Im\213\321%r\370\366d\206h\230\026\324\244\\\314]e\266\222lpHP\375\355"
"\271\332^\25FW\247\215\235\204\220\330\253\0\214\274\323\n\367\344X\05\270"
"\263E\6\320,\036\217\312?\17\2\301\257\275\3\1\023\212k:\221\21AOg\334\352"
"\227\362\317\316\360\264\346s\226\254t\"\347\2555\205\342\3717\350\34u\337"
"nG\361\32q\35)\305\211o\267b\16\252\30\276\33\374V>K\306\322y \232\333\300"
"\376x\315Z\364\037\335\2503\210\a\3071\261\22\20Y\'\200\354_`Q\177\251\031"
"\265J\r-\345z\237\223\311\234\357\240\340;M\256*\365\260\310\353\273<\203S"
"\231a\027+\004~\272w\326&\341i\024cU!\f}";
#endif
/*----------------------------------------------------------------------------*\
Data types and private variables
\*----------------------------------------------------------------------------*/
/** The array that stores all round keys during the AES key-expansion process */
static uint8_t RoundKey[BLOCKSIZE * ROUNDS + KEYSIZE];
/** block_t indicates fixed-size memory blocks, and state_t represents the state
* matrix. note that state[i][j] means the i-th COLUMN and j-th ROW of matrix */
typedef uint8_t block_t[BLOCKSIZE];
typedef uint8_t state_t[Nb][4];
/*----------------------------------------------------------------------------*\
Auxiliary functions for the Rijndael algorithm
\*----------------------------------------------------------------------------*/
#define SBoxValue(x) ( sbox[x])
#define InvSBoxValue(x) (rsbox[x]) /* omitted dynamic s-box calculation */
#define COPYDWORD(x, y) *(int32_t*) &y = *(int32_t*) &x
#define XOR32BITS(x, y) *(int32_t*) &y ^= *(int32_t*) &x
#if DISCARD_SUBROUTINES
/** note: 'long long' type is NOT supported in C89. so this may throw errors: */
#define xorBlock(x, y) \
( \
*(long long*) &(y)[0] ^= *(long long const*) &(x)[0], \
*(long long*) &(y)[8] ^= *(long long const*) &(x)[8] \
)
#define xtime(x) ((x) & 0x80 ? (x) * 2 ^ 0x11b : (x) << 1)
#define mixG8(a, b, c, d) b ^ c ^ d ^ \
xtime(a ^ b ^ xtime(a ^ c ^ xtime(a ^ b ^ c ^ d )))
#else
/** XOR two 128bit numbers (blocks) called src and dest, so that: dest ^= src */
static void xorBlock( const block_t src, block_t dest )
{
uint8_t i;
for (i = 0; i < BLOCKSIZE; ++i) /* many CPUs have single instruction */
{ /* such as XORPS for 128-bit-xor. */
dest[i] ^= src[i]; /* see the file: x86-improvements */
}
}
/** doubling in GF(2^8): left-shift and if carry bit is set, xor it with 0x1b */
static uint8_t xtime( uint8_t x )
{
return (x > 0x7f) * 0x1b ^ (x << 1);
}
#if DECRYPTION
/** inverse multiply in 8bit GF: mul(a,14) ^ mul(b,11) ^ mul(c,13) ^ mul(d,9) */
static uint8_t mixG8( uint8_t a, uint8_t b, uint8_t c, uint8_t d )
{
b ^= a;
d ^= b ^ c;
c ^= a;
a ^= d;
c ^= xtime( d );
b ^= xtime( c );
a ^= xtime( b );
return a; /* or use (9 11 13 14) lookup tables */
}
#endif
#endif
/*----------------------------------------------------------------------------*\
Main functions for the Rijndael encryption algorithm
\*----------------------------------------------------------------------------*/
/** This function produces (ROUNDS+1) round keys, which are used in each round
* to encrypt/decrypt the intermediate states. First round key is the main key
* itself, and other rounds are constructed from the previous ones as follows */
static void KeyExpansion( const uint8_t* key )
{
uint8_t rcon = 1, i;
memcpy( RoundKey, key, KEYSIZE );
for (i = KEYSIZE; i < BLOCKSIZE * (ROUNDS + 1); i += 4)
{
switch (i % KEYSIZE)
{
case 0:
memcpy( &RoundKey[i], &RoundKey[i - KEYSIZE], KEYSIZE );
/* RCON reaches 0 only in AES-128, otherwise the line is ignored. */
if (4 / Nk && rcon == 0) rcon = 0x1b;
RoundKey[i ] ^= SBoxValue( RoundKey[i - 3] ) ^ rcon;
RoundKey[i + 1] ^= SBoxValue( RoundKey[i - 2] );
RoundKey[i + 2] ^= SBoxValue( RoundKey[i - 1] );
RoundKey[i + 3] ^= SBoxValue( RoundKey[i - 4] );
rcon <<= 1;
break;
#if AES___== 256
case 48 - KEYSIZE:
RoundKey[i ] ^= SBoxValue( RoundKey[i - 4] );
RoundKey[i + 1] ^= SBoxValue( RoundKey[i - 3] );
RoundKey[i + 2] ^= SBoxValue( RoundKey[i - 2] );
RoundKey[i + 3] ^= SBoxValue( RoundKey[i - 1] );
break;
#endif
default:
XOR32BITS( RoundKey[ i - 4 ], RoundKey[ i ] );
break;
}
}
}
/** Add the round keys to the rijndael state matrix (adding in GF means XOR). */
static void AddRoundKey( const uint8_t round, block_t state )
{
xorBlock( RoundKey + BLOCKSIZE * round, state );
}
/** Substitute values in the state matrix with associated values in the S-box */
static void SubBytes( block_t state )
{
uint8_t i;
for (i = 0; i < BLOCKSIZE; ++i)
{
state[i] = SBoxValue( state[i] );
}
}
/** Shift/rotate the rows of the state matrix to the left. Each row is shifted
* with a different offset (= Row number). So the "zeroth" row is not shifted */
static void ShiftRows( state_t state )
{
uint8_t tmp = state[0][1];
state[0][1] = state[1][1];
state[1][1] = state[2][1];
state[2][1] = state[3][1];
state[3][1] = tmp; /* the first row rotates 1 column(s) to left */
tmp = state[0][2];
state[0][2] = state[2][2];
state[2][2] = tmp;
tmp = state[1][2];
state[1][2] = state[3][2];
state[3][2] = tmp; /* the second row rotates 2 columns to left, */
tmp = state[0][3];
state[0][3] = state[3][3];
state[3][3] = state[2][3];
state[2][3] = state[1][3];
state[1][3] = tmp; /* and the 3rd row rotates 3 columns to left */
}
/** Use matrix multiplication in Galois field to mix the columns of the state */
static void MixColumns( state_t state )
{
uint8_t C[4], i;
for (i = 0; i < Nb; ++i) /*-> https://crypto.stackexchange.com/q/2402 */
{
COPYDWORD( state[i], C[0] );
C[3] ^= C[1];
C[1] ^= C[0];
C[0] ^= C[2];
C[2] = xtime( C[0] );
C[0] ^= C[3]; /* C[0] = xor of all elements in i-th column */
C[0] ^= xtime( C[1] );
C[1] = xtime( C[3] );
state[i][0] ^= C[0];
state[i][1] ^= C[0] ^= C[2];
state[i][2] ^= C[0] ^= C[1];
state[i][3] ^= C[0] ^= C[2];
}
}
/** Encrypt a plaintext input block and save the result/ciphertext as output. */
static void rijndaelEncrypt( const block_t input, block_t output )
{
uint8_t r;
state_t* mat = (void*) output;
/* copy plaintext into the state matrix, and beware of undefined behavior */
if (input != output) memcpy( mat, input, BLOCKSIZE );
/* The encryption is carried out in #ROUNDS iterations, of which the first
* #ROUNDS-1 are identical. The last round doesn't involve mixing columns */
for (r = 0; r != ROUNDS; )
{
AddRoundKey( r, output );
SubBytes( output );
ShiftRows( *mat );
++r != ROUNDS ? MixColumns( *mat ) : AddRoundKey( ROUNDS, output );
}
}
/*----------------------------------------------------------------------------*\
Block-decryption part of the Rijndael algorithm
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(DECRYPTION)
/** Substitutes the values in state matrix with values of the inverted S-box. */
static void InvSubBytes( block_t state )
{
uint8_t i;
for (i = 0; i < BLOCKSIZE; ++i)
{
state[i] = InvSBoxValue( state[i] );
}
}
/** This function shifts (i.e rotates) the rows of the state matrix to right. */
static void InvShiftRows( state_t state )
{
uint8_t tmp = state[3][1];
state[3][1] = state[2][1];
state[2][1] = state[1][1];
state[1][1] = state[0][1];
state[0][1] = tmp; /* the first row rotates 1 columns to right, */
tmp = state[0][2];
state[0][2] = state[2][2];
state[2][2] = tmp;
tmp = state[1][2];
state[1][2] = state[3][2];
state[3][2] = tmp; /* the second row rotates 2 columns to right */
tmp = state[0][3];
state[0][3] = state[1][3];
state[1][3] = state[2][3];
state[2][3] = state[3][3];
state[3][3] = tmp; /* the third row rotates 3 columns to right. */
}
/** Reverse the process of mixing columns by matrix multiplication in GF(2^8) */
static void InvMixColumns( state_t state )
{
uint8_t C[4], i;
for (i = 0; i < Nb; ++i) /*-> https://crypto.stackexchange.com/q/2569 */
{
COPYDWORD( state[i], C[0] );
state[i][0] = mixG8( C[0], C[1], C[2], C[3] );
state[i][1] = mixG8( C[1], C[2], C[3], C[0] );
state[i][2] = mixG8( C[2], C[3], C[0], C[1] );
state[i][3] = mixG8( C[3], C[0], C[1], C[2] );
}
}
/** Decrypt a ciphertext input block and save the result/plaintext to output. */
static void rijndaelDecrypt( const block_t input, block_t output )
{
uint8_t r;
state_t* mat = (void*) output;
/* copy input to the state matrix, i.e initialize the state by ciphertext */
if (input != output) memcpy( mat, input, BLOCKSIZE );
/* Decryption is carried out in #ROUNDS iterations. The rounds are similar
* except for the first one which doesn't involve [reverse]mixing columns */
for (r = ROUNDS; r != 0; )
{
r-- != ROUNDS ? InvMixColumns( *mat ) : AddRoundKey( ROUNDS, output );
InvShiftRows( *mat );
InvSubBytes( output );
AddRoundKey( r, output );
}
}
#endif /* DECRYPTION */
#if MICRO_RJNDL
/**
* @brief encrypt or decrypt a single block with a given key
* @param key a byte array with a fixed size of KEYSIZE
* @param mode mode of operation: 'E' (1) to encrypt, 'D' (0) to decrypt
* @param x input byte array with BLOCKSIZE bytes
* @param y output byte array with BLOCKSIZE bytes
*/
void AES_Cipher( const uint8_t* key, const char mode, const block_t x, block_t y )
{
KeyExpansion( key );
mode & 1 ? rijndaelEncrypt( x, y ) : rijndaelDecrypt( x, y );
}
#endif
/*----------------------------------------------------------------------------*\
* Implementation of different block ciphers modes *
* Definitions & Auxiliary Functions *
\*----------------------------------------------------------------------------*/
/** function-pointer types, indicating functions that take fixed-size blocks: */
typedef void (*fmix_t)( const block_t, block_t ) SDCC_REENT;
typedef void (*fdouble_t)( block_t );
#define AES_setkey(key) KeyExpansion( key )
#if INCREASE_SECURITY
#define BURN(key) memset( key, 0, sizeof key )
#define SABOTAGE(buf, len) memset( buf, 0, len )
#define MISMATCH constmemcmp /* a.k.a secure memcmp */
#else
#define MISMATCH memcmp
#define SABOTAGE(buf, len) (void) buf
#define BURN(key) (void) key /* the line will be ignored */
#endif
#if INCREASE_SECURITY && AEAD_MODES
/** for constant-time comparison of memory blocks, to avoid "timing attacks". */
static uint8_t constmemcmp( const uint8_t* src, const uint8_t* dst, uint8_t n )
{
uint8_t cmp = 0;
while (n--)
{
cmp |= src[n] ^ dst[n];
}
return cmp;
}
#endif
#if SMALL_CIPHER
typedef uint8_t count_t;
#define incBlock(block, index) ++block[index]
#define xorBEint(buf, num, pos) buf[pos - 1] ^= (num) >> 8, buf[pos] ^= num
#define copyLint(buf, num, pos) buf[pos + 1] = (num) >> 8, buf[pos] = num
#else
typedef size_t count_t;
#if XTS || GCM_SIV
/** copy a little endian integer to the block, with LSB at specified position */
static void copyLint( block_t block, size_t num, uint8_t pos )
{
do
block[pos++] = (uint8_t) num;
while (num >>= 8);
}
#endif
#if CTR || KWA || FPE
/** xor a byte array with a big-endian integer, whose LSB is at specified pos */
static void xorBEint( uint8_t* buff, size_t num, uint8_t pos )
{
do
buff[pos--] ^= (uint8_t) num;
while (num >>= 8);
}
#endif
#if CTR
/** increment the value of a 128-bit counter block, regarding its endian-ness */
static void incBlock( block_t block, uint8_t index )
{
do /* increment the LSBs, */
if (++block[index]) /* ..until no overflow */
break;
while ((index < 4 && ++index < 4) || --index > 8);
}
#endif
#endif /* SMALL CIPHER */
#if EAX && !EAXP || SIV || OCB || CMAC
/** Multiply a block by two in Galois bit field GF(2^128): big-endian version */
static void doubleBblock( block_t array )
{
int c = 0, i;
for (i = BLOCKSIZE; i > 0; c >>= 8) /* from last byte (LSB) to */
{ /* first: left-shift, then */
c |= array[--i] << 1; /* append the previous MSBit */
array[i] = (uint8_t) c;
} /* if first MSBit is carried */
array[LAST] ^= c * 0x87; /* .. B ^= 10000111b (B.E.) */
}
#endif
#if XTS || EAXP
/** Multiply a block by two in Galois field GF(2^128): little-endian version. */
static void doubleLblock( block_t array )
{
int i, c = 0;
for (i = 0; i < BLOCKSIZE; c >>= 8) /* the same as doubleBblock */
{ /* ..but with reversed bytes */
c |= array[i] << 1;
array[i++] = (uint8_t) c;
}
array[0] ^= c * 0x87; /* B ^= 10000111b (L.E.) */
}
#endif
#if GCM
/** Divide a 128-bit big-endian integer by two in Galois bit field GF(2^128). */
static void divideBblock( block_t array )
{
unsigned i, c = 0;
for (i = 0; i < BLOCKSIZE; ++i) /* from first to last byte, */
{ /* prepend the previous LSB */
c = c << 8 | array[i]; /* then shift it to right. */
array[i] = c >> 1;
} /* if block is odd (LSB = 1) */
if (c & 1) array[0] ^= 0xe1; /* .. B ^= 11100001b << 120 */
}
/** Multiply two 128-bit numbers (big-endian blocks) in the Galois bit field. */
static void mulGF128( const block_t x, block_t y )
{
uint8_t b, i;
block_t result = { 0 }; /* working memory */
for (i = 0; i < BLOCKSIZE; ++i)
{
for (b = 0x80; b; b >>= 1) /* check all the bits of X, */
{
if (x[i] & b) /* ..and if any bit is set, */
{
xorBlock( y, result ); /* ..add Y to the result */
}
divideBblock( y ); /* Y_next = (Y / 2) in GF */
}
}
memcpy( y, result, sizeof result ); /* result is saved into y */
}
#endif /* GCM */
#if GCM_SIV
/** Divide a block by two in 128-bit Galois field: the little-endian version. */
static void divideLblock( block_t array )
{
unsigned c = 0, i;
for (i = BLOCKSIZE; i--; ) /* similar to divideBblock ↑ */
{ /* ..but with reversed bytes */
c = c << 8 | array[i];
array[i] = c >> 1;
}
if (c & 1) array[LAST] ^= 0xe1; /* B ^= LE. 11100001b << 120 */
}
/** The so-called "dot multiplying" in GF(2^128), used in POLYVAL calculation */
static void dotGF128( const block_t x, block_t y )
{
uint8_t b, i;
block_t result = { 0 };
for (i = BLOCKSIZE; i--; )
{
for (b = 0x80; b; b >>= 1) /* pretty much the same as */
{ /* ..(reversed) mulGF128 */
divideLblock( y );
if (x[i] & b)
{
xorBlock( y, result );
}
}
}
memcpy( y, result, sizeof result ); /* result is saved into y */
}
#endif /* GCM-SIV */
#if CTR || CFB || OFB || CTS || OCB
/** mix/cipher the block B and then xor the result with n bytes of X to get Y */
static void mixThenXor( fmix_t mix, const block_t B, block_t f,
const uint8_t* X, uint8_t n, uint8_t* Y )
{
if (n != 0)
{
mix( B, f ); /* Y = f(B) ^ X */
while (n--)
{
Y[n] = f[n] ^ X[n];
}
}
}
#endif
#if AEAD_MODES || FPE
/** xor the result with input data and then apply the digest/mixing function.
* repeat this process for each block of data, until all blocks are digested. */
static void xMac( const void* data, const size_t dataSize,
const block_t seed, fmix_t mix, block_t result )
{
uint8_t const* x;
count_t n = dataSize / BLOCKSIZE; /* number of full blocks */
for (x = data; n--; x += BLOCKSIZE)
{
xorBlock( x, result ); /* M_next = mix(seed, M ^ X) */
mix( seed, result );
}
if ((n = dataSize % BLOCKSIZE) != 0) /* if any partial block left */
{
while (n--)
{
result[n] ^= x[n];
}
mix( seed, result );
}
}
#endif
#if CMAC || SIV || EAX || OCB
/** calculate CMAC of input data using pre-calculated keys: K1 (D) and K2 (Q) */
static void cMac( const block_t K1, const block_t K2,
const void* data, const size_t dataSize, block_t mac )
{
const uint8_t s = dataSize ? (dataSize - 1) % BLOCKSIZE + 1 : 0;
const uint8_t *k = K1, *ps = s ? (uint8_t*) data + dataSize - s : &s;
xMac( data, dataSize - s, mac, &rijndaelEncrypt, mac );
if (s < BLOCKSIZE)
{
mac[s] ^= 0x80; /* pad( M_last; K1, K2 ) */
k = K2;
}
xorBlock( k, mac );
xMac( ps, s + !s, mac, &rijndaelEncrypt, mac );
}
/** calculate key-dependent constants D and Q using a given doubling function */
static void getSubkeys( fdouble_t gfdouble, const char quad,
const uint8_t* key, block_t D, block_t Q )
{
AES_setkey( key );
rijndaelEncrypt( D, D ); /* H or L_* = Enc(zeros) */
if (quad)
{
gfdouble( D ); /* D or L_$ = double(L_*) */
}
memcpy( Q, D, BLOCKSIZE );
gfdouble( Q ); /* Q or L_0 = double(L_$) */
}
#endif
#ifdef AES_PADDING
/** in ECB mode & CBC without CTS, the last (partial) block has to be padded. */
static char padBlock( const uint8_t len, block_t block )
{
uint8_t n = BLOCKSIZE - len, *p = &block[len];
#if AES_PADDING
memset( p, n * (AES_PADDING != 2), n );
*p ^= (0x80) * (AES_PADDING == 2); /* either PKCS#7 / IEC7816-4 */
#else
memset( p, 0, n % BLOCKSIZE ); /* default (zero) padding */
#endif
return len || AES_PADDING;
}
#endif
/*----------------------------------------------------------------------------*\
ECB-AES (electronic codebook mode) functions
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(ECB)
/**
* @brief encrypt the input plaintext using ECB-AES block-cipher method
* @param key encryption key with a fixed size specified by KEYSIZE
* @param pntxt input plaintext buffer
* @param ptextLen size of plaintext in bytes
* @param crtxt resulting cipher-text buffer
*/
void AES_ECB_encrypt( const uint8_t* key,
const void* pntxt, const size_t ptextLen, void* crtxt )
{
uint8_t* y;
count_t n = ptextLen / BLOCKSIZE; /* number of full blocks */
memcpy( crtxt, pntxt, ptextLen ); /* copy plaintext to output */
AES_setkey( key );
for (y = crtxt; n--; y += BLOCKSIZE)
{
rijndaelEncrypt( y, y ); /* C = Enc(P) */
}
if (padBlock( ptextLen % BLOCKSIZE, y ))
{
rijndaelEncrypt( y, y );
}
BURN( RoundKey );
}
/**
* @brief decrypt the input ciphertext using ECB-AES block-cipher method
* @param key decryption key with a fixed size specified by KEYSIZE
* @param crtxt input ciphertext buffer
* @param crtxtLen size of ciphertext in bytes
* @param pntxt resulting plaintext buffer
* @return error if the ciphertext has a partial block
*/
char AES_ECB_decrypt( const uint8_t* key,
const void* crtxt, const size_t crtxtLen, void* pntxt )
{
uint8_t* y;
count_t n = crtxtLen / BLOCKSIZE;
memcpy( pntxt, crtxt, crtxtLen ); /* do in-place decryption */
AES_setkey( key );
for (y = pntxt; n--; y += BLOCKSIZE)
{
rijndaelDecrypt( y, y ); /* P = Dec(C) */
}
BURN( RoundKey );
/* if padding is enabled, check whether the result is properly padded. error
* must be thrown if it's not. here we skip that and just check the size. */
return crtxtLen % BLOCKSIZE ? M_DECRYPTION_ERROR : M_RESULT_SUCCESS;
}
#endif /* ECB */
/*----------------------------------------------------------------------------*\
CBC-AES (cipher block chaining) functions
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(CBC)
/**
* @brief encrypt the input plaintext using CBC-AES block-cipher method
* @param key encryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param pntxt input plaintext buffer
* @param ptextLen size of plaintext in bytes
* @param crtxt resulting cipher-text buffer
* @return error in CTS mode, if plaintext is a single partial block
*/
char AES_CBC_encrypt( const uint8_t* key, const block_t iVec,
const void* pntxt, const size_t ptextLen, void* crtxt )
{
uint8_t const* iv = iVec;
uint8_t r = ptextLen % BLOCKSIZE, *y;
count_t n = ptextLen / BLOCKSIZE;
#if CTS
if (n > 1 && !r && --n) r = BLOCKSIZE; /* CS3 ciphertext stealing */
if (n == 0) return M_ENCRYPTION_ERROR; /* data size >= BLOCKSIZE */
#endif
memcpy( crtxt, pntxt, ptextLen ); /* do in-place encryption */
AES_setkey( key );
for (y = crtxt; n--; y += BLOCKSIZE)
{
xorBlock( iv, y ); /* C = Enc(IV ^ P) */
rijndaelEncrypt( y, y ); /* IV_next = C */
iv = y;
}
#if CTS
if (r)
{
block_t L = { 0 };
memcpy( L, y, r ); /* backup the last chunk */
memcpy( y, y - BLOCKSIZE, r ); /* 'steal' the cipher-text */
y -= BLOCKSIZE; /* ..to fill the last chunk */
iv = L;
#else
if (padBlock( r, y ))
{
#endif
xorBlock( iv, y );
rijndaelEncrypt( y, y );
}
BURN( RoundKey );
return M_RESULT_SUCCESS;
}
/**
* @brief decrypt the input ciphertext using CBC-AES block-cipher method
* @param key decryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param crtxt input ciphertext buffer
* @param crtxtLen size of ciphertext in bytes
* @param pntxt resulting plaintext buffer
* @return error if the size of ciphertext is not a valid value
*/
char AES_CBC_decrypt( const uint8_t* key, const block_t iVec,
const void* crtxt, const size_t crtxtLen, void* pntxt )
{
uint8_t const *x = crtxt, *iv = iVec;
uint8_t r = crtxtLen % BLOCKSIZE, *y;
count_t n = crtxtLen / BLOCKSIZE;
#if CTS
if (n > 1 && !r && --n) r = BLOCKSIZE;
if (n == 0) return M_DECRYPTION_ERROR;
#else
if (r != 0) return M_DECRYPTION_ERROR;
#endif
n -= r > 0; /* hold last 2 blocks in CTS */
AES_setkey( key );
for (y = pntxt; n--; y += BLOCKSIZE)
{
rijndaelDecrypt( x, y ); /* P = Dec(C) ^ IV */
xorBlock( iv, y ); /* IV_next = C */
iv = x;
x += BLOCKSIZE;
#if CTS
}
if (r)
{ /* last two blocks: {X, Z} */
const uint8_t* z = x + BLOCKSIZE;
mixThenXor( &rijndaelDecrypt, x, y, z, r, y + BLOCKSIZE );
memcpy( y, z, r );
rijndaelDecrypt( y, y ); /* P2 = Z ^ Dec(X) = Z ^ Y */
xorBlock( iv, y ); /* P1 = IV ^ Dec(Z | *Y) */
#endif
}
BURN( RoundKey );
return M_RESULT_SUCCESS;
}
#endif /* CBC */
/*----------------------------------------------------------------------------*\
CFB-AES (cipher feedback) functions
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(CFB)
/**
* @brief the general scheme of CFB-AES block-ciphering algorithm
* @param key encryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param mode mode of operation: (1) to encrypt, (0) to decrypt
* @param input buffer of the input plain/cipher-text
* @param dataSize size of input in bytes
* @param output buffer of the resulting cipher/plain-text
*/
static void CFB_cipher( const uint8_t* key, const block_t iVec, const char mode,
const void* input, const size_t dataSize, void* output )
{
uint8_t const *iv = iVec, *x = input;
uint8_t* y;
block_t tmp;
count_t n = dataSize / BLOCKSIZE; /* number of full blocks */
AES_setkey( key );
for (y = output; n--; y += BLOCKSIZE)
{
rijndaelEncrypt( iv, y ); /* both in en[de]cryption: */
xorBlock( x, y ); /* Y = Enc(IV) ^ X */
iv = mode ? y : x; /* IV_next = Ciphertext */
x += BLOCKSIZE;
}
mixThenXor( &rijndaelEncrypt, iv, tmp, x, dataSize % BLOCKSIZE, y );
BURN( RoundKey );
}
/**
* @brief encrypt the input plaintext using CFB-AES block-cipher method
* @param key encryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param pntxt input plaintext buffer
* @param ptextLen size of plaintext in bytes
* @param crtxt resulting cipher-text buffer
*/
void AES_CFB_encrypt( const uint8_t* key, const block_t iVec,
const void* pntxt, const size_t ptextLen, void* crtxt )
{
CFB_cipher( key, iVec, 1, pntxt, ptextLen, crtxt );
}
/**
* @brief decrypt the input ciphertext using CFB-AES block-cipher method
* @param key decryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param crtxt input ciphertext buffer
* @param crtxtLen size of ciphertext in bytes
* @param pntxt resulting plaintext buffer
*/
void AES_CFB_decrypt( const uint8_t* key, const block_t iVec,
const void* crtxt, const size_t crtxtLen, void* pntxt )
{
CFB_cipher( key, iVec, 0, crtxt, crtxtLen, pntxt );
}
#endif /* CFB */
/*----------------------------------------------------------------------------*\
OFB-AES (output feedback) functions
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(OFB)
/**
* @brief encrypt the input plaintext using OFB-AES block-cipher method
* @param key encryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param pntxt input plaintext buffer
* @param ptextLen size of plaintext in bytes
* @param crtxt resulting cipher-text buffer
*/
void AES_OFB_encrypt( const uint8_t* key, const block_t iVec,
const void* pntxt, const size_t ptextLen, void* crtxt )
{
count_t n = ptextLen / BLOCKSIZE;
uint8_t* y;
block_t iv;
memcpy( iv, iVec, sizeof iv );
memcpy( crtxt, pntxt, ptextLen ); /* i.e. in-place encryption */
AES_setkey( key );
for (y = crtxt; n--; y += BLOCKSIZE)
{
rijndaelEncrypt( iv, iv ); /* IV_next = Enc(IV) */
xorBlock( iv, y ); /* C = IV_next ^ P */
}
mixThenXor( &rijndaelEncrypt, iv, iv, y, ptextLen % BLOCKSIZE, y );
BURN( RoundKey );
}
/**
* @brief decrypt the input ciphertext using OFB-AES block-cipher method
* @param key decryption key with a fixed size specified by KEYSIZE
* @param iVec initialization vector
* @param crtxt input ciphertext buffer
* @param crtxtLen size of ciphertext in bytes
* @param pntxt resulting plaintext buffer
*/
void AES_OFB_decrypt( const uint8_t* key, const block_t iVec,
const void* crtxt, const size_t crtxtLen, void* pntxt )
{
AES_OFB_encrypt( key, iVec, crtxt, crtxtLen, pntxt );
}
#endif /* OFB */
/*----------------------------------------------------------------------------*\
Parallelizable, counter-based modes of AES: demonstrating the main idea
+ How to use it in a simple, non-authenticated API
\*----------------------------------------------------------------------------*/
#if CTR
/**
* @brief the general scheme of operation in block-counter mode
* @param iCtr initialized counter block
* @param mode specifies the "counter based" block-cipher or AEAD mode
* @param input buffer of the input plain/cipher-text
* @param dataSize size of input in bytes
* @param output buffer of the resulting cipher/plain-text
*/
static void CTR_cipher( const block_t iCtr, const char mode,
const void* input, const size_t dataSize, void* output )
{
block_t c, enc;
count_t n = dataSize / BLOCKSIZE;
uint8_t index = LAST, *y;
memcpy( output, input, dataSize ); /* do in-place en/decryption */
memcpy( c, iCtr, sizeof c );
switch (mode)
{
case 2:
incBlock( c, index ); /* pre-increment in CCM/GCM */
break;
case 4:
c[+8] &= 0x7F; /* SIV mode: clear two bits */
c[12] &= 0x7F;
break;
case 8: /* GCM-SIV: set one bit */
c[index] |= 0x80;
index = 0;
break;
}
for (y = output; n--; y += BLOCKSIZE)
{
rijndaelEncrypt( c, enc ); /* both in en[de]cryption: */
xorBlock( enc, y ); /* Y = Enc(Ctr) ^ X */
incBlock( c, index ); /* Ctr_next = Ctr + 1 */
}
mixThenXor( &rijndaelEncrypt, c, c, y, dataSize % BLOCKSIZE, y );
}
#endif
#if IMPLEMENT(CTR_NA)
/**
* @brief encrypt the input plaintext using CTR-AES block-cipher method
* @param key encryption key with a fixed size specified by KEYSIZE
* @param iv initialization vector a.k.a. nonce
* @param pntxt input plaintext buffer
* @param ptextLen size of plaintext in bytes
* @param crtxt resulting cipher-text buffer
*/
void AES_CTR_encrypt( const uint8_t* key, const uint8_t* iv,
const void* pntxt, const size_t ptextLen, void* crtxt )
{
#if CTR_IV_LENGTH == 16
uint8_t const* ctr = iv; /* block is pre-initialized */
#else
block_t ctr = { 0 };
memcpy( ctr, iv, CTR_IV_LENGTH );
xorBEint( ctr, CTR_STARTVALUE, LAST ); /* initialize the counter */
#endif
AES_setkey( key );
CTR_cipher( ctr, 0, pntxt, ptextLen, crtxt );
BURN( RoundKey );
}
/**
* @brief decrypt the input ciphertext using CTR-AES block-cipher method
* @param key decryption key with a fixed size specified by KEYSIZE
* @param iv initialization vector a.k.a. nonce
* @param crtxt input ciphertext buffer
* @param crtxtLen size of ciphertext in bytes
* @param pntxt resulting plaintext buffer
*/
void AES_CTR_decrypt( const uint8_t* key, const uint8_t* iv,
const void* crtxt, const size_t crtxtLen, void* pntxt )
{
AES_CTR_encrypt( key, iv, crtxt, crtxtLen, pntxt );
}
#endif /* CTR */
/*----------------------------------------------------------------------------*\
XEX-AES based modes (xor-encrypt-xor): the basic idea
+ main functions of XTS-AES (XEX Tweaked-codebook with ciphertext Stealing)
\*----------------------------------------------------------------------------*/
#if IMPLEMENT(XTS)
/**
* @brief encrypt or decrypt a data unit with XTS method
* @param keypair pair of encryption keys, each one has KEYSIZE bytes
* @param mode mode of operation: encrypting (1) or decrypting (0)
* @param tweak data unit identifier block, similar to nonce in CTR mode
* @param sectid sector id: in case of a null tweak, use this instead
* @param dataSize size of input data, to be encrypted/decrypted
* @param storage result of encryption/decryption process
*/
static void XTS_cipher( const uint8_t* keypair, const char mode,