summaryrefslogtreecommitdiff
path: root/utility/encryption/aes_reference.c
blob: b3a5c05402296f7ae7783606e3a1f869dfa5f50f (plain)
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
/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support 
 * ----------------------------------------------------------------------------
 * Copyright (c) 2008, Atmel Corporation
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ----------------------------------------------------------------------------
 */

//------------------------------------------------------------------------------
// Firmware encryption using AES reference implementation
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "aes_reference.h"

#if defined(USE_ENCRYPTION) && defined(ENCRYPTION_AES_REF)
#include <stdio.h>
#include <string.h>
#include <board.h>
#include <utility/trace.h>
#include <utility/assert.h>
#include <pmc/pmc.h>

//------------------------------------------------------------------------------
// Global variables
//------------------------------------------------------------------------------
#define word8 static unsigned char
#define word32 static unsigned int

#include "boxes-ref.dat"

static unsigned char shifts[3][2][4] = {
    {{0,1,2,3}, {0,3,2,1}},
    {{0,1,2,3}, {0,5,4,3}},
    {{0,7,5,5}, {0,1,3,4}}
};

static unsigned char key[KC][4];
static unsigned char expandedKey[ROUNDS+1][BC][4];
static unsigned int T0[256], T1[256], T2[256], T3[256], TF[256];

#if defined(ENCRYPTION_CBC) || defined(ENCRYPTION_CTR)
static unsigned char IV[BC][4];
#endif

//------------------------------------------------------------------------------
// Inline functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Multiply two elements of GF(2^m) needed for MixColumn and InvMixColumn
/// \param a first element
/// \param b second element
/// \return  result of operation
//------------------------------------------------------------------------------
static unsigned char mul(unsigned char a, unsigned char b)
{
    if (a && b) {
        return Alogtable[(Logtable[a] + Logtable[b])%255];
    }
    else {
        return 0;
    }
}

//------------------------------------------------------------------------------
/// Returns the minimum between two numbers
/// \param First number
/// \param Second number
/// \return Minimum between the two operands
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
static unsigned int min(unsigned int number1, unsigned int number2)
{
    if (number1 > number2) {
        return number2;
    }
    else {
        return number1;
    }
}
#endif

//------------------------------------------------------------------------------
/// XOR text and round key together
/// \param Plain text
/// \param Round key
//------------------------------------------------------------------------------
static inline void addRoundKey(unsigned char a[BC][4], const unsigned char rk[BC][4])
{
    unsigned int i;

    for (i=0; i < BC; i++) {
        ((int *) a)[i] ^= ((int *) rk)[i];
    }
}

//------------------------------------------------------------------------------
/// Performs the AES key schedule
/// \param Key to use
/// \param Buffer to store expanded key schedule
//------------------------------------------------------------------------------
static inline void keySchedule(unsigned char k[KC][4], unsigned char W[ROUNDS+1][BC][4])
{
    int t;
    int rconpointer = 0;
    unsigned int j;
    unsigned char tk[KC][4];

    for(j=0; j < KC; j++) {
        ((int *) tk)[j] = ((int *) k)[j];
    }
  
    t = 0;
    /* copy values into round key array */
    for(j=0; (j < KC) && (t < (ROUNDS+1)*BC); j++, t++) {
        ((int *) W[t / BC])[t%BC] = ((int *) tk)[j];
    }
  
    while (t < (ROUNDS+1)*BC) { 

        tk[0][0] ^= S[tk[KC-1][1]] ^ rcon[rconpointer++];
        tk[0][1] ^= S[tk[KC-1][2]];
        tk[0][2] ^= S[tk[KC-1][3]];
        tk[0][3] ^= S[tk[KC-1][0]];

        if (KC != 8) {
            for(j=1; j < KC; j++) {
                ((int *) tk)[j] ^= ((int *) tk)[j-1];
            }
        }
        else {
            for(j=1; j < KC/2; j++) {
                ((int *) tk)[j] ^= ((int *) tk)[j-1];
            }
            tk[KC/2][0] ^= S[tk[KC/2 - 1][0]];
            tk[KC/2][1] ^= S[tk[KC/2 - 1][1]];
            tk[KC/2][2] ^= S[tk[KC/2 - 1][2]];
            tk[KC/2][3] ^= S[tk[KC/2 - 1][3]];

            for(j=KC/2+1; j < KC; j++) {
                ((int *) tk)[j] ^= ((int *) tk)[j-1];
            }
        }

        // copy values into round key array
        for(j=0; (j < KC) && (t < (ROUNDS+1)*BC); j++, t++) {
            ((int *) W[t/BC])[t%BC] = ((int *) tk)[j];
        }
    }
}

//------------------------------------------------------------------------------
/// Performs the AES inverse key schedule
/// \param Key to use
/// \param Buffer to store expanded key schedule
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB) || defined(ENCRYPTION_CBC)
static inline void invKeySchedule(unsigned char k[KC][4], 
                                  unsigned char W[ROUNDS+1][BC][4]) 
{
    unsigned int r;
    unsigned int j;
    unsigned char tmp[4];
  
    // Expand key normally
    keySchedule(k, W);
  
    // Apply invMixColumns to all rounds except first and last one
    for (r=1; r < ROUNDS; r++) {
        for (j=0; j < BC; j++) {
            tmp[0] = mul(0x0E, W[r][j][0]) ^ mul(0x0B, W[r][j][1]) ^
                     mul(0x0D, W[r][j][2]) ^ mul(0x09, W[r][j][3]);
            tmp[1] = mul(0x0E, W[r][j][1]) ^ mul(0x0B, W[r][j][2]) ^
                     mul(0x0D, W[r][j][3]) ^ mul(0x09, W[r][j][0]);
            tmp[2] = mul(0x0E, W[r][j][2]) ^ mul(0x0B, W[r][j][3]) ^
                     mul(0x0D, W[r][j][0]) ^ mul(0x09, W[r][j][1]);
            tmp[3] = mul(0x0E, W[r][j][3]) ^ mul(0x0B, W[r][j][0]) ^
                     mul(0x0D, W[r][j][1]) ^ mul(0x09, W[r][j][2]);
            W[r][j][0] = tmp[0];
            W[r][j][1] = tmp[1];
            W[r][j][2] = tmp[2];
            W[r][j][3] = tmp[3];
        }
    }
}
#endif

//------------------------------------------------------------------------------
/// Perform the RotBytes operation needed by the AES cipher
/// \param input to rotate
/// \return Rotated word
//------------------------------------------------------------------------------
static inline unsigned int rotBytes(unsigned int input) 
{
    return ((input << 8) | (input >> 24));
}

//------------------------------------------------------------------------------
/// Generates the lookup tables needed for encryption
/// \param Pointer to t0
/// \param Pointer to t1
/// \param Pointer to t2
/// \param Pointer to t3
/// \param Pointer to tf
/// \param Box
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
static inline void generateEncryptionLUTs(unsigned int * t0,
                                          unsigned int * t1,
                                          unsigned int * t2,
                                          unsigned int * t3,
                                          unsigned int * tf,
                                          unsigned char box[256])
{
    unsigned int a;

    for (a=0; a <= 255; a++) {
        // Calc t0
        t0[a] = (mul(2, box[a])) |
                (box[a] << 8) |
                (box[a] << 16) |
                (mul(3, box[a]) << 24);
        
        // Calc t1, t2, t3
        t1[a] = rotBytes(t0[a]);
        t2[a] = rotBytes(t1[a]);
        t3[a] = rotBytes(t2[a]);
        
        // Calc tf
        tf[a] = box[a] | (box[a] << 8) | (box[a] << 16) | (box[a] << 24);
    }
}
#endif

//------------------------------------------------------------------------------
/// Generates the lookup tables needed for decryption
/// \param Pointer to t0
/// \param Pointer to t1
/// \param Pointer to t2
/// \param Pointer to t3
/// \param Pointer to tf
/// \param Box
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB) || defined(ENCRYPTION_CBC)
static inline void generateDecryptionLUTs(unsigned int * t0,
                                          unsigned int * t1,
                                          unsigned int * t2,
                                          unsigned int * t3,
                                          unsigned int * tf,
                                          unsigned char box[256])
{
    unsigned int a;

    for (a=0; a <= 255; a++) {
   
        // Calc t0
        t0[a] = (mul(0x0E, box[a])) |
                (mul(0x09, box[a]) << 8) |
                (mul(0x0D, box[a]) << 16) |
                (mul(0x0B, box[a]) << 24);
        
        // Calc t1, t2, t3
        t1[a] = rotBytes(t0[a]);
        t2[a] = rotBytes(t1[a]);
        t3[a] = rotBytes(t2[a]);
        
        // Calc tf
        tf[a] = box[a] | (box[a] << 8) | (box[a] << 16) | (box[a] << 24);
    }
}
#endif

//------------------------------------------------------------------------------
/// Copies a block to a buffer
/// \param Block to copy
/// \param Buffer to store copy
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
static void copyBlock(unsigned char input[BC][4], unsigned char output[BC][4])
{
    unsigned int j; 

    for (j=0; j < BC; j++) {
        ((int *) output)[j] = ((int *) input)[j];
    }
}
#endif

//------------------------------------------------------------------------------
///  Encrypts a block of plain text using precalculated LUTs
/// \param Block of plain text to encrypt
/// \param Expanded key
/// \param Pointer to t0
/// \param Pointer to t1
/// \param Pointer to t2
/// \param Pointer to t3
/// \param Pointer to tf
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
static inline void encrypt(unsigned char a[BC][4],
                           const unsigned char rk[ROUNDS+1][BC][4],
                           unsigned int * t0,
                           unsigned int * t1,
                           unsigned int * t2,
                           unsigned int * t3,
                           unsigned int * tf) 
{
    unsigned char b[BC][4];
    unsigned int r;
    unsigned int j;
                            
    // First key addition
    addRoundKey(a, rk[0]);

    // ROUNDS-1 ordinary rounds
    for(r=1; r < ROUNDS; r++) {
        for (j=0; j < BC; j++) {
     
            ((int *) b)[j] = t0[a[j][0]] ^
                           t1[a[(j+shifts[SC][0][1])%BC][1]] ^
                           t2[a[(j+shifts[SC][0][2])%BC][2]] ^
                           t3[a[(j+shifts[SC][0][3])%BC][3]] ^
                           ((int *) rk[r])[j];
        }
        if ((++r) == ROUNDS) {          
            break;
        }
        for (j=0; j < BC; j++) {
            ((int *) a)[j] = t0[b[j][0]] ^
                           t1[b[(j+shifts[SC][0][1])%BC][1]] ^
                           t2[b[(j+shifts[SC][0][2])%BC][2]] ^
                           t3[b[(j+shifts[SC][0][3])%BC][3]] ^
                           ((int *) rk[r])[j];
        }
    }
  
    // Last round (no MixColumns)
    for (j=0; j < BC; j++) {
        ((int *) a)[j] = (t0f[b[j][0]]) ^
                         (t1f[b[(j+shifts[SC][0][1])%BC][1]]) ^
                         (t2f[b[(j+shifts[SC][0][2])%BC][2]]) ^
                         (t3f[b[(j+shifts[SC][0][3])%BC][3]]) ^
                         ((int *) rk[ROUNDS])[j];
    }
}
#endif

//------------------------------------------------------------------------------
/// Decrypts a block of plain text using precalculated LUTs
/// \param Block of cipher text to decrypt
/// \param Expanded key
/// \param Pointer to t0
/// \param Pointer to t1
/// \param Pointer to t2
/// \param Pointer to t3
/// \param Pointer to tf
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB) || defined(ENCRYPTION_CBC)
static inline void decrypt(unsigned char a[BC][4],
                           const unsigned char rk[ROUNDS+1][BC][4],
                           unsigned int * t0,
                           unsigned int * t1,
                           unsigned int * t2,
                           unsigned int * t3,
                           unsigned int * tf)
{
    unsigned char b[BC][4];
    unsigned int r;
    unsigned int j;
                            
    // First key addition
    addRoundKey(a, rk[ROUNDS]);

    // ROUNDS-1 ordinary rounds
    for(r=ROUNDS-1; r > 0; r--) {
        for (j=0; j < BC; j++) {
            ((int *) b)[j] = t0[a[j][0]] ^
                           t1[a[(j+shifts[SC][1][1])%BC][1]] ^
                           t2[a[(j+shifts[SC][1][2])%BC][2]] ^
                           t3[a[(j+shifts[SC][1][3])%BC][3]] ^
                           ((int *) rk[r])[j];
        }
        if ((--r) == 0) {
            break;
        }
        for (j=0; j < BC; j++) {
            ((int *) a)[j] = t0[b[j][0]] ^
                           t1[b[(j+shifts[SC][1][1])%BC][1]] ^
                           t2[b[(j+shifts[SC][1][2])%BC][2]] ^
                           t3[b[(j+shifts[SC][1][3])%BC][3]] ^
                           ((int *) rk[r])[j];
        }
    }
    // Last round (no MixColumns)
    for (j=0; j < BC; j++) {
        ((int *) a)[j] = (t0f[b[j][0]]) ^
                         (t1f[b[(j+shifts[SC][1][1])%BC][1]]) ^
                         (t2f[b[(j+shifts[SC][1][2])%BC][2]]) ^
                         (t3f[b[(j+shifts[SC][1][3])%BC][3]]) ^
                         ((int *) rk[0])[j];
    }
}
#endif

//------------------------------------------------------------------------------
/// Converts an ASCII hexadecimal representation to a raw binary one
/// \param ASCII value
/// \param Buffer to store binary value
/// \param Size of value
//------------------------------------------------------------------------------
static void ASCII2RawHex(const unsigned char * ascii, 
                         unsigned char * binary, 
                         unsigned int length) 
{
    unsigned char * ptr;
    unsigned int i;

    ptr = (unsigned char *) binary;
    for (i=0; i < length; i++, ptr++, ascii++) {
        if (*ascii >= 'A') {
            *ptr = *ascii - 'A' + 10;
        }
        else {
            *ptr = *ascii - '0';
        }
        *ptr <<= 4;
        ascii++;
        if (*ascii >= 'A') {
            *ptr += *ascii - 'A' + 10;
        }
        else {
            *ptr += *ascii - '0';
        }
    }
}

//------------------------------------------------------------------------------
/// Decrypts a cipher text using ECB mode
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text
/// \param Expanded key to use
/// \return 0 if successful, 0 otherwise
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB)
static unsigned int ecb_decrypt(const unsigned char * cipherText,
                         unsigned char * plainText,
                         unsigned int length,
                         unsigned char expandedKey[ROUNDS+1][BC][4])
{
    unsigned char block[BC][4];
    unsigned int i;
    unsigned int l;

    // Check input parameters
    if ((cipherText == NULL) || (plainText == NULL) || (expandedKey == NULL)) {
        TRACE_DEBUG("AES/REF: NULL parameter(s).\n\r");
        return 0;
    }
    if (length%ENCRYPTION_BLOCK_LENGTH != 0) {
        TRACE_DEBUG("AES/REF: Data length must be a multiple of the cipher block size.\n\r");
        return 0;
    }
    // ECB decryption
    for (l=0; l < length;) {
        // Copy cipher text block, decrypt it and copy result
        for (i=0; i < ENCRYPTION_BLOCK_LENGTH; i++) {
            ((char *) block)[i] = cipherText[l+i];
        }
        decrypt(block, expandedKey, T0, T1, T2, T3, TF);
        for (i=0; i < ENCRYPTION_BLOCK_LENGTH; i++) {
            plainText[l+i] = ((char *) block)[i];
        }
        l += ENCRYPTION_BLOCK_LENGTH;
    }

    return 1;
}
#endif

//------------------------------------------------------------------------------
/// Decrypts a cipher text using CBC mode
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text (in bytes)
/// \param Expanded key to use
/// \param Initialization vector to use
/// \return 1 if successful, 0 otherwise */
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CBC)
static unsigned int cbc_decrypt(const unsigned char * cipherText,
                                       unsigned char * plainText,
                                       unsigned int length,
                                       const unsigned char expandedKey[ROUNDS+1][BC][4],
                                       unsigned char IV[BC][4])
{             
    unsigned char block[BC][4];
    unsigned int i;
    unsigned int l;

    // Check input parameters
    if ((cipherText == NULL) || (plainText == NULL)) {
        TRACE_DEBUG("AES/REF: NULL parameter(s).\n\r");
        return 0;
    }
    if (length%ENCRYPTION_BLOCK_LENGTH != 0) {
        TRACE_DEBUG("AES/REF: Cipher text length must be a multiple of the cipher block length.\n\r");
        return 0;
    }
    // Decrypt data
    for (l=0; l < length;) {
        // Copy and decrypt a block of cipher text
        for (i=0; i < BC; i++) {
            ((int *) block)[i] = ((int *) &cipherText[l])[i];
        }
        decrypt(block, expandedKey, T0, T1, T2, T3, TF);
        // Xor decrypted text & IV, copy new IV
        for (i=0; i < BC; i++) {
            unsigned int tmp = ((int *) block)[i] ^ ((int *) IV)[i];
            ((int *) IV)[i] = ((int *) &cipherText[l])[i];
            ((int *) &plainText[l])[i] = tmp;
        }

        // Loop progression
        l += ENCRYPTION_BLOCK_LENGTH;
    }
    return 1;
}
#endif

//------------------------------------------------------------------------------
/// Decrypts a cipher text using CTR mode
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text
/// \param Expanded key to use
/// \param Initialization vector to use
/// \return 1 if successful, 0 otherwise
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
static unsigned int ctr_decrypt(const unsigned char * cipherText,
                                       unsigned char * plainText,
                                       unsigned int length,
                                       const unsigned char expandedKey[ROUNDS+1][BC][4],
                                       unsigned char IV[BC][4])
{
    unsigned char block[BC][4];
    unsigned int bytes;
    unsigned int i;
    unsigned int l;
    int k;

    // Check input parameters
    if ((cipherText == NULL) || (plainText == NULL)) {
        return 0;
    }
    for (l=0; l < length;) {
        // Copy counter and encrypt it
        copyBlock(IV, block);
        encrypt(block, expandedKey, T0, T1, T2, T3, TF);

        // XOR current plain text block with encrypted counter
        bytes = min(length - l, ENCRYPTION_BLOCK_LENGTH);

        for (i=0; i < bytes; i++) {
            plainText[l+i] = cipherText[l+i] ^ ((char *) block)[i];
        }
        // Increment counter (big-endian) and number of encrypted bytes
        for (k=ENCRYPTION_BLOCK_LENGTH-1; k >= 0; k--) {
            if (++((char *) IV)[k] != 0) {
                break;
            }
        }
        l += bytes;
    }
    return 1;
}
#endif

//------------------------------------------------------------------------------
// Functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Initializes the AES algorithm
//------------------------------------------------------------------------------
#ifdef ONLY_ONE_ENCRYPTION
void aes_ref_init(void)
{
    TRACE_DEBUG("AES/REF: Initializing ...\n\r");

    ASCII2RawHex((unsigned char*)ENCRYPTION_KEY, (unsigned char*)key, ENCRYPTION_KEY_LENGTH);

#if defined(ENCRYPTION_ECB) || defined(ENCRYPTION_CBC)

    // Initialize key schedule
    invKeySchedule(key, expandedKey);

    // Generate lookup tables
    generateDecryptionLUTs(T0, T1, T2, T3, TF, Si);

#elif defined(ENCRYPTION_CTR)

    // Initialize key schedule
    keySchedule(key, expandedKey);

    // Generate lookup tables
    generateEncryptionLUTs(T0, T1, T2, T3, TF, S);
#endif
  
#if defined(ENCRYPTION_CBC) || defined(ENCRYPTION_CTR)
    // Initialize counter
    ASCII2RawHex((unsigned char*)ENCRYPTION_IV, (unsigned char*)IV, ENCRYPTION_BLOCK_LENGTH);
#endif

    TRACE_DEBUG("AES/REF: Initialization done.\n\r");
}
#endif

//------------------------------------------------------------------------------
/// Initializes the AES algorithm mode CBC
//------------------------------------------------------------------------------
#ifndef ONLY_ONE_ENCRYPTION
#if defined(ENCRYPTION_CBC)
void aes_ref_init_CBC(void)
{
    TRACE_DEBUG("aes_ref_init_CBC\n\r");

    ASCII2RawHex((unsigned char*)ENCRYPTION_KEY, (unsigned char*)key, ENCRYPTION_KEY_LENGTH);

    // Initialize key schedule
    invKeySchedule(key, expandedKey);

    // Generate lookup tables
    generateDecryptionLUTs(T0, T1, T2, T3, TF, Si);

    // Initialize counter
    ASCII2RawHex((unsigned char*)ENCRYPTION_IV, (unsigned char*)IV, ENCRYPTION_BLOCK_LENGTH);

    TRACE_DEBUG("AES/REF: Initialization done.\n\r");
}
#endif

//------------------------------------------------------------------------------
/// Initializes the AES algorithm mode ECB
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB)
void aes_ref_init_ECB(void)
{
    TRACE_DEBUG("aes_ref_init_ECB\n\r");

    ASCII2RawHex((unsigned char*)ENCRYPTION_KEY, (unsigned char*)key, ENCRYPTION_KEY_LENGTH);

    // Initialize key schedule
    invKeySchedule(key, expandedKey);

    // Generate lookup tables
    generateDecryptionLUTs(T0, T1, T2, T3, TF, Si);

    TRACE_DEBUG("AES/REF: Initialization done.\n\r");
}
#endif

//------------------------------------------------------------------------------
/// Initializes the AES algorithm mode CTR
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
void aes_ref_init_CTR(void)
{
    TRACE_DEBUG("aes_ref_init_CTR\n\r");

    ASCII2RawHex((unsigned char*)ENCRYPTION_KEY, (unsigned char*)key, ENCRYPTION_KEY_LENGTH);

    // Initialize key schedule
    keySchedule(key, expandedKey);

    // Generate lookup tables
    generateEncryptionLUTs(T0, T1, T2, T3, TF, S);

    // Initialize counter
    ASCII2RawHex((unsigned char*)ENCRYPTION_IV, (unsigned char*)IV, ENCRYPTION_BLOCK_LENGTH);

    TRACE_DEBUG("AES/REF: Initialization done.\n\r");
}
#endif
#endif // ONLY_ONE_ENCRYPTION

//------------------------------------------------------------------------------
/// Cleanup the AES algorithm
//------------------------------------------------------------------------------
void aes_ref_cleanup(void)
{
    TRACE_DEBUG("AES/REF: Cleaning up ...\n\r");
    TRACE_DEBUG("AES/REF: Cleanup done.\n\r");
}

//------------------------------------------------------------------------------
/// Decrypt a cipher text of variable length
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text (in bytes)
/// \return 1 if decryption was successful, 0 otherwise.
//------------------------------------------------------------------------------
#ifdef ONLY_ONE_ENCRYPTION
int aes_ref_decrypt(const unsigned char * cipherText,
                    unsigned char * plainText,
                    unsigned int length)
{
    TRACE_DEBUG("aes_ref_decrypt\n\r");
#if defined(ENCRYPTION_ECB)
    return ecb_decrypt(cipherText, plainText, length, expandedKey);
#elif defined(ENCRYPTION_CBC)
    return cbc_decrypt(cipherText, plainText, length, expandedKey, IV);;
#elif defined(ENCRYPTION_CTR)
    return ctr_decrypt(cipherText, plainText, length, expandedKey, IV);
#endif
}
#endif

//------------------------------------------------------------------------------
/// Decrypt a cipher text of variable length, mode CBC
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text (in bytes)
/// \return 1 if decryption was successful, 0 otherwise.
//------------------------------------------------------------------------------
#ifndef ONLY_ONE_ENCRYPTION
#if defined(ENCRYPTION_CBC)
int aes_ref_decrypt_CBC(const unsigned char * cipherText,
                    unsigned char * plainText,
                    unsigned int length)
{
    TRACE_DEBUG("aes_ref_decrypt_CBC\n\r");
    return cbc_decrypt(cipherText, plainText, length, expandedKey, IV);;
}
#endif

//------------------------------------------------------------------------------
/// Decrypt a cipher text of variable length, mode ECB
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text (in bytes)
/// \return 1 if decryption was successful, 0 otherwise.
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_ECB)
int aes_ref_decrypt_ECB(const unsigned char * cipherText,
                    unsigned char * plainText,
                    unsigned int length)
{
    TRACE_DEBUG("aes_ref_decrypt_ECB\n\r");
    return ecb_decrypt(cipherText, plainText, length, expandedKey);
}
#endif

//------------------------------------------------------------------------------
/// Decrypt a cipher text of variable length, mode CTR
/// \param Cipher text to decrypt
/// \param Buffer to store plain text
/// \param Length of cipher text (in bytes)
/// \return 1 if decryption was successful, 0 otherwise.
//------------------------------------------------------------------------------
#if defined(ENCRYPTION_CTR)
int aes_ref_decrypt_CTR(const unsigned char * cipherText,
                    unsigned char * plainText,
                    unsigned int length)
{
    TRACE_DEBUG("aes_ref_decrypt_CTR\n\r");
    return ctr_decrypt(cipherText, plainText, length, expandedKey, IV);
}
#endif

#endif // ONLY_ONE_ENCRYPTION

#endif // defined(USE_ENCRYPTION) && defined(ENCRYPTION_AES_REF)



personal git repositories of Harald Welte. Your mileage may vary