• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  ---------------------------------------------------------------------------
3  Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.
4 
5  LICENSE TERMS
6 
7  The free distribution and use of this software in both source and binary
8  form is allowed (with or without changes) provided that:
9 
10    1. distributions of this source code include the above copyright
11       notice, this list of conditions and the following disclaimer;
12 
13    2. distributions in binary form include the above copyright
14       notice, this list of conditions and the following disclaimer
15       in the documentation and/or other associated materials;
16 
17    3. the copyright holder's name is not used to endorse products
18       built using this software without specific written permission.
19 
20  ALTERNATIVELY, provided that this notice is retained in full, this product
21  may be distributed under the terms of the GNU General Public License (GPL),
22  in which case the provisions of the GPL apply INSTEAD OF those given above.
23 
24  DISCLAIMER
25 
26  This software is provided 'as is' with no explicit or implied warranties
27  in respect of its properties, including, but not limited to, correctness
28  and/or fitness for purpose.
29  ---------------------------------------------------------------------------
30  Issue 28/01/2004
31 
32  My thanks go to Dag Arne Osvik for devising the schemes used here for key
33  length derivation from the form of the key schedule
34 
35  This file contains the compilation options for AES (Rijndael) and code
36  that is common across encryption, key scheduling and table generation.
37 
38  OPERATION
39 
40  These source code files implement the AES algorithm Rijndael designed by
41  Joan Daemen and Vincent Rijmen. This version is designed for the standard
42  block size of 16 bytes and for key sizes of 128, 192 and 256 bits (16, 24
43  and 32 bytes).
44 
45  This version is designed for flexibility and speed using operations on
46  32-bit words rather than operations on bytes.  It can be compiled with
47  either big or little endian internal byte order but is faster when the
48  native byte order for the processor is used.
49 
50  THE CIPHER INTERFACE
51 
52  The cipher interface is implemented as an array of bytes in which lower
53  AES bit sequence indexes map to higher numeric significance within bytes.
54 
55   aes_08t                 (an unsigned  8-bit type)
56   aes_32t                 (an unsigned 32-bit type)
57   struct aes_encrypt_ctx  (structure for the cipher encryption context)
58   struct aes_decrypt_ctx  (structure for the cipher decryption context)
59   aes_rval                the function return type
60 
61   C subroutine calls:
62 
63   aes_rval aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]);
64   aes_rval aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]);
65   aes_rval aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]);
66   aes_rval aes_encrypt(const unsigned char *in, unsigned char *out,
67                                                   const aes_encrypt_ctx cx[1]);
68 
69   aes_rval aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]);
70   aes_rval aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]);
71   aes_rval aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]);
72   aes_rval aes_decrypt(const unsigned char *in, unsigned char *out,
73                                                   const aes_decrypt_ctx cx[1]);
74 
75  IMPORTANT NOTE: If you are using this C interface with dynamic tables make sure that
76  you call genTabs() before AES is used so that the tables are initialised.
77 
78  C++ aes class subroutines:
79 
80      Class AESencrypt  for encryption
81 
82       Construtors:
83           AESencrypt(void)
84           AESencrypt(const unsigned char *key) - 128 bit key
85       Members:
86           aes_rval key128(const unsigned char *key)
87           aes_rval key192(const unsigned char *key)
88           aes_rval key256(const unsigned char *key)
89           aes_rval encrypt(const unsigned char *in, unsigned char *out) const
90 
91       Class AESdecrypt  for encryption
92       Construtors:
93           AESdecrypt(void)
94           AESdecrypt(const unsigned char *key) - 128 bit key
95       Members:
96           aes_rval key128(const unsigned char *key)
97           aes_rval key192(const unsigned char *key)
98           aes_rval key256(const unsigned char *key)
99           aes_rval decrypt(const unsigned char *in, unsigned char *out) const
100 
101     COMPILATION
102 
103     The files used to provide AES (Rijndael) are
104 
105     a. aes.h for the definitions needed for use in C.
106     b. aescpp.h for the definitions needed for use in C++.
107     c. aesopt.h for setting compilation options (also includes common code).
108     d. aescrypt.c for encryption and decrytpion, or
109     e. aeskey.c for key scheduling.
110     f. aestab.c for table loading or generation.
111     g. aescrypt.asm for encryption and decryption using assembler code.
112     h. aescrypt.mmx.asm for encryption and decryption using MMX assembler.
113 
114     To compile AES (Rijndael) for use in C code use aes.h and set the
115     defines here for the facilities you need (key lengths, encryption
116     and/or decryption). Do not define AES_DLL or AES_CPP.  Set the options
117     for optimisations and table sizes here.
118 
119     To compile AES (Rijndael) for use in in C++ code use aescpp.h but do
120     not define AES_DLL
121 
122     To compile AES (Rijndael) in C as a Dynamic Link Library DLL) use
123     aes.h and include the AES_DLL define.
124 
125     CONFIGURATION OPTIONS (here and in aes.h)
126 
127     a. set AES_DLL in aes.h if AES (Rijndael) is to be compiled as a DLL
128     b. You may need to set PLATFORM_BYTE_ORDER to define the byte order.
129     c. If you want the code to run in a specific internal byte order, then
130        ALGORITHM_BYTE_ORDER must be set accordingly.
131     d. set other configuration options decribed below.
132 */
133 
134 #if !defined( _AESOPT_H )
135 #define _AESOPT_H
136 
137 #include "aes.h"
138 
139 /*  CONFIGURATION - USE OF DEFINES
140 
141     Later in this section there are a number of defines that control the
142     operation of the code.  In each section, the purpose of each define is
143     explained so that the relevant form can be included or excluded by
144     setting either 1's or 0's respectively on the branches of the related
145     #if clauses.
146 
147     PLATFORM SPECIFIC INCLUDES AND BYTE ORDER IN 32-BIT WORDS
148 
149     To obtain the highest speed on processors with 32-bit words, this code
150     needs to determine the byte order of the target machine. The following
151     block of code is an attempt to capture the most obvious ways in which
152     various environemnts define byte order. It may well fail, in which case
153     the definitions will need to be set by editing at the points marked
154     **** EDIT HERE IF NECESSARY **** below.  My thanks go to Peter Gutmann
155     for his assistance with this endian detection nightmare.
156 */
157 
158 #define BRG_LITTLE_ENDIAN   1234 /* byte 0 is least significant (i386) */
159 #define BRG_BIG_ENDIAN      4321 /* byte 0 is most significant (mc68k) */
160 
161 #if defined(__GNUC__) || defined(__GNU_LIBRARY__)
162 #  if defined(__FreeBSD__) || defined(__OpenBSD__)
163 #    include <sys/endian.h>
164 #  elif defined( BSD ) && BSD >= 199103
165 #      include <machine/endian.h>
166 #  elif defined(__APPLE__)
167 #    if defined(__BIG_ENDIAN__) && !defined( BIG_ENDIAN )
168 #      define BIG_ENDIAN
169 #    elif defined(__LITTLE_ENDIAN__) && !defined( LITTLE_ENDIAN )
170 #      define LITTLE_ENDIAN
171 #    endif
172 #  else
173 #    include <stdio.h>  /* for detecting newlib */
174 #    if defined(_NEWLIB_VERSION)
175 #      include <sys/param.h> /* doesn't help with newlib 1.13 because it doesnt define LITTLE/BIG_ENDIAN */
176 #    else
177 #      include <endian.h>
178 #    endif
179 #    if defined(__BEOS__)
180 #      include <byteswap.h>
181 #    endif
182 #  endif
183 #endif
184 
185 #if !defined(PLATFORM_BYTE_ORDER)
186 #  if defined(LITTLE_ENDIAN) || defined(BIG_ENDIAN)
187 #    if    defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
188 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
189 #    elif !defined(LITTLE_ENDIAN) &&  defined(BIG_ENDIAN)
190 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
191 #    elif defined(BYTE_ORDER) && (BYTE_ORDER == LITTLE_ENDIAN)
192 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
193 #    elif defined(BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
194 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
195 #    endif
196 #  elif defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)
197 #    if    defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
198 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
199 #    elif !defined(_LITTLE_ENDIAN) &&  defined(_BIG_ENDIAN)
200 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
201 #    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _LITTLE_ENDIAN)
202 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
203 #    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _BIG_ENDIAN)
204 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
205 #   endif
206 #  elif defined(__LITTLE_ENDIAN__) || defined(__BIG_ENDIAN__)
207 #    if    defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
208 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
209 #    elif !defined(__LITTLE_ENDIAN__) &&  defined(__BIG_ENDIAN__)
210 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
211 #    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __LITTLE_ENDIAN__)
212 #      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
213 #    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __BIG_ENDIAN__)
214 #      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
215 #    endif
216 #  endif
217 #endif
218 
219 /*  if the platform is still unknown, try to find its byte order    */
220 /*  from commonly used machine defines                              */
221 
222 #if !defined(PLATFORM_BYTE_ORDER)
223 
224 #if   defined( __alpha__ ) || defined( __alpha ) || defined( i386 )       || \
225       defined( __i386__ )  || defined( _M_I86 )  || defined( _M_IX86 )    || \
226       defined( __OS2__ )   || defined( sun386 )  || defined( __TURBOC__ ) || \
227       defined( vax )       || defined( vms )     || defined( VMS )        || \
228       defined( __VMS )
229 #  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
230 
231 #elif defined( AMIGA )    || defined( applec )  || defined( __AS400__ )  || \
232       defined( _CRAY )    || defined( __hppa )  || defined( __hp9000 )   || \
233       defined( ibm370 )   || defined( mc68000 ) || defined( m68k )       || \
234       defined( __MRC__ )  || defined( __MVS__ ) || defined( __MWERKS__ ) || \
235       defined( sparc )    || defined( __sparc)  || defined( SYMANTEC_C ) || \
236       defined( __TANDEM ) || defined( THINK_C ) || defined( __VMCMS__ )
237 #  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
238 
239 #elif defined(_WIN32_WCE) || !defined(JBED_BIG_ENDIAN)    /* **** EDIT HERE IF NECESSARY **** */
240 #  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
241 #elif defined(JBED_BIG_ENDIAN)     /* **** EDIT HERE IF NECESSARY **** */
242 #  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
243 #else
244 #  error Please edit aesopt.h (line 239 or 241) to set the platform byte order
245 #endif
246 
247 #endif
248 
249 /*  SOME LOCAL DEFINITIONS  */
250 
251 #define NO_TABLES              0
252 #define ONE_TABLE              1
253 #define FOUR_TABLES            4
254 #define NONE                   0
255 #define PARTIAL                1
256 #define FULL                   2
257 
258 #if defined(bswap32)
259 #define aes_sw32    bswap32
260 #elif defined(bswap_32)
261 #define aes_sw32    bswap_32
262 #else
263 #define brot(x,n)   (((aes_32t)(x) <<  n) | ((aes_32t)(x) >> (32 - n)))
264 #define aes_sw32(x) ((brot((x),8) & 0x00ff00ff) | (brot((x),24) & 0xff00ff00))
265 #endif
266 
267 /*  1. FUNCTIONS REQUIRED
268 
269     This implementation provides subroutines for encryption, decryption
270     and for setting the three key lengths (separately) for encryption
271     and decryption. When the assembler code is not being used the following
272     definition blocks allow the selection of the routines that are to be
273     included in the compilation.
274 */
275 #if defined( AES_ENCRYPT )
276 #define ENCRYPTION
277 #define ENCRYPTION_KEY_SCHEDULE
278 #endif
279 
280 #if defined( AES_DECRYPT )
281 #define DECRYPTION
282 #define DECRYPTION_KEY_SCHEDULE
283 #endif
284 
285 /*  2. ASSEMBLER SUPPORT
286 
287     This define (which can be on the command line) enables the use of the
288     assembler code routines for encryption and decryption with the C code
289     only providing key scheduling
290 */
291 #if 0 && !defined(AES_ASM)
292 #define AES_ASM
293 #endif
294 
295 /*  3. BYTE ORDER WITHIN 32 BIT WORDS
296 
297     The fundamental data processing units in Rijndael are 8-bit bytes. The
298     input, output and key input are all enumerated arrays of bytes in which
299     bytes are numbered starting at zero and increasing to one less than the
300     number of bytes in the array in question. This enumeration is only used
301     for naming bytes and does not imply any adjacency or order relationship
302     from one byte to another. When these inputs and outputs are considered
303     as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to
304     byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte.
305     In this implementation bits are numbered from 0 to 7 starting at the
306     numerically least significant end of each byte (bit n represents 2^n).
307 
308     However, Rijndael can be implemented more efficiently using 32-bit
309     words by packing bytes into words so that bytes 4*n to 4*n+3 are placed
310     into word[n]. While in principle these bytes can be assembled into words
311     in any positions, this implementation only supports the two formats in
312     which bytes in adjacent positions within words also have adjacent byte
313     numbers. This order is called big-endian if the lowest numbered bytes
314     in words have the highest numeric significance and little-endian if the
315     opposite applies.
316 
317     This code can work in either order irrespective of the order used by the
318     machine on which it runs. Normally the internal byte order will be set
319     to the order of the processor on which the code is to be run but this
320     define can be used to reverse this in special situations
321 
322     NOTE: Assembler code versions rely on PLATFORM_BYTE_ORDER being set
323 */
324 #if 1 || defined(AES_ASM)
325 #define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER
326 #elif 0
327 #define ALGORITHM_BYTE_ORDER BRG_LITTLE_ENDIAN
328 #elif 0
329 #define ALGORITHM_BYTE_ORDER BRG_BIG_ENDIAN
330 #else
331 #error The algorithm byte order is not defined
332 #endif
333 
334 /*  4. FAST INPUT/OUTPUT OPERATIONS.
335 
336     On some machines it is possible to improve speed by transferring the
337     bytes in the input and output arrays to and from the internal 32-bit
338     variables by addressing these arrays as if they are arrays of 32-bit
339     words.  On some machines this will always be possible but there may
340     be a large performance penalty if the byte arrays are not aligned on
341     the normal word boundaries. On other machines this technique will
342     lead to memory access errors when such 32-bit word accesses are not
343     properly aligned. The option SAFE_IO avoids such problems but will
344     often be slower on those machines that support misaligned access
345     (especially so if care is taken to align the input  and output byte
346     arrays on 32-bit word boundaries). If SAFE_IO is not defined it is
347     assumed that access to byte arrays as if they are arrays of 32-bit
348     words will not cause problems when such accesses are misaligned.
349 */
350 #if 1 && !defined(_MSC_VER)
351 #define SAFE_IO
352 #endif
353 
354 /*  5. LOOP UNROLLING
355 
356     The code for encryption and decrytpion cycles through a number of rounds
357     that can be implemented either in a loop or by expanding the code into a
358     long sequence of instructions, the latter producing a larger program but
359     one that will often be much faster. The latter is called loop unrolling.
360     There are also potential speed advantages in expanding two iterations in
361     a loop with half the number of iterations, which is called partial loop
362     unrolling.  The following options allow partial or full loop unrolling
363     to be set independently for encryption and decryption
364 */
365 #if 1
366 #define ENC_UNROLL  FULL
367 #elif 0
368 #define ENC_UNROLL  PARTIAL
369 #else
370 #define ENC_UNROLL  NONE
371 #endif
372 
373 #if 1
374 #define DEC_UNROLL  FULL
375 #elif 0
376 #define DEC_UNROLL  PARTIAL
377 #else
378 #define DEC_UNROLL  NONE
379 #endif
380 
381 /*  6. FAST FINITE FIELD OPERATIONS
382 
383     If this section is included, tables are used to provide faster finite
384     field arithmetic (this has no effect if FIXED_TABLES is defined).
385 */
386 #if 1
387 #define FF_TABLES
388 #endif
389 
390 /*  7. INTERNAL STATE VARIABLE FORMAT
391 
392     The internal state of Rijndael is stored in a number of local 32-bit
393     word varaibles which can be defined either as an array or as individual
394     names variables. Include this section if you want to store these local
395     varaibles in arrays. Otherwise individual local variables will be used.
396 */
397 #if 1
398 #define ARRAYS
399 #endif
400 
401 /* In this implementation the columns of the state array are each held in
402    32-bit words. The state array can be held in various ways: in an array
403    of words, in a number of individual word variables or in a number of
404    processor registers. The following define maps a variable name x and
405    a column number c to the way the state array variable is to be held.
406    The first define below maps the state into an array x[c] whereas the
407    second form maps the state into a number of individual variables x0,
408    x1, etc.  Another form could map individual state colums to machine
409    register names.
410 */
411 
412 #if defined(ARRAYS)
413 #define s(x,c) x[c]
414 #else
415 #define s(x,c) x##c
416 #endif
417 
418 /*  8. FIXED OR DYNAMIC TABLES
419 
420     When this section is included the tables used by the code are compiled
421     statically into the binary file.  Otherwise the subroutine gen_tabs()
422     must be called to compute them before the code is first used.
423 */
424 #if 1
425 #define FIXED_TABLES
426 #endif
427 
428 /*  9. TABLE ALIGNMENT
429 
430     On some sytsems speed will be improved by aligning the AES large lookup
431     tables on particular boundaries. This define should be set to a power of
432     two giving the desired alignment. It can be left undefined if alignment
433     is not needed.  This option is specific to the Microsft VC++ compiler -
434     it seems to sometimes cause trouble for the VC++ version 6 compiler.
435 */
436 
437 #if 0 && defined(_MSC_VER) && (_MSC_VER >= 1300)
438 #define TABLE_ALIGN 64
439 #endif
440 
441 /*  10. INTERNAL TABLE CONFIGURATION
442 
443     This cipher proceeds by repeating in a number of cycles known as 'rounds'
444     which are implemented by a round function which can optionally be speeded
445     up using tables.  The basic tables are each 256 32-bit words, with either
446     one or four tables being required for each round function depending on
447     how much speed is required. The encryption and decryption round functions
448     are different and the last encryption and decrytpion round functions are
449     different again making four different round functions in all.
450 
451     This means that:
452       1. Normal encryption and decryption rounds can each use either 0, 1
453          or 4 tables and table spaces of 0, 1024 or 4096 bytes each.
454       2. The last encryption and decryption rounds can also use either 0, 1
455          or 4 tables and table spaces of 0, 1024 or 4096 bytes each.
456 
457     Include or exclude the appropriate definitions below to set the number
458     of tables used by this implementation.
459 */
460 
461 #if 1   /* set tables for the normal encryption round */
462 #define ENC_ROUND   FOUR_TABLES
463 #elif 0
464 #define ENC_ROUND   ONE_TABLE
465 #else
466 #define ENC_ROUND   NO_TABLES
467 #endif
468 
469 #if 1   /* set tables for the last encryption round */
470 #define LAST_ENC_ROUND  FOUR_TABLES
471 #elif 0
472 #define LAST_ENC_ROUND  ONE_TABLE
473 #else
474 #define LAST_ENC_ROUND  NO_TABLES
475 #endif
476 
477 #if 1   /* set tables for the normal decryption round */
478 #define DEC_ROUND   FOUR_TABLES
479 #elif 0
480 #define DEC_ROUND   ONE_TABLE
481 #else
482 #define DEC_ROUND   NO_TABLES
483 #endif
484 
485 #if 1   /* set tables for the last decryption round */
486 #define LAST_DEC_ROUND  FOUR_TABLES
487 #elif 0
488 #define LAST_DEC_ROUND  ONE_TABLE
489 #else
490 #define LAST_DEC_ROUND  NO_TABLES
491 #endif
492 
493 /*  The decryption key schedule can be speeded up with tables in the same
494     way that the round functions can.  Include or exclude the following
495     defines to set this requirement.
496 */
497 #if 1
498 #define KEY_SCHED   FOUR_TABLES
499 #elif 0
500 #define KEY_SCHED   ONE_TABLE
501 #else
502 #define KEY_SCHED   NO_TABLES
503 #endif
504 
505 /* END OF CONFIGURATION OPTIONS */
506 
507 #define RC_LENGTH   (5 * (AES_BLOCK_SIZE / 4 - 2))
508 
509 /* Disable or report errors on some combinations of options */
510 
511 #if ENC_ROUND == NO_TABLES && LAST_ENC_ROUND != NO_TABLES
512 #undef  LAST_ENC_ROUND
513 #define LAST_ENC_ROUND  NO_TABLES
514 #elif ENC_ROUND == ONE_TABLE && LAST_ENC_ROUND == FOUR_TABLES
515 #undef  LAST_ENC_ROUND
516 #define LAST_ENC_ROUND  ONE_TABLE
517 #endif
518 
519 #if ENC_ROUND == NO_TABLES && ENC_UNROLL != NONE
520 #undef  ENC_UNROLL
521 #define ENC_UNROLL  NONE
522 #endif
523 
524 #if DEC_ROUND == NO_TABLES && LAST_DEC_ROUND != NO_TABLES
525 #undef  LAST_DEC_ROUND
526 #define LAST_DEC_ROUND  NO_TABLES
527 #elif DEC_ROUND == ONE_TABLE && LAST_DEC_ROUND == FOUR_TABLES
528 #undef  LAST_DEC_ROUND
529 #define LAST_DEC_ROUND  ONE_TABLE
530 #endif
531 
532 #if DEC_ROUND == NO_TABLES && DEC_UNROLL != NONE
533 #undef  DEC_UNROLL
534 #define DEC_UNROLL  NONE
535 #endif
536 
537 /*  upr(x,n):  rotates bytes within words by n positions, moving bytes to
538                higher index positions with wrap around into low positions
539     ups(x,n):  moves bytes by n positions to higher index positions in
540                words but without wrap around
541     bval(x,n): extracts a byte from a word
542 
543     NOTE:      The definitions given here are intended only for use with
544                unsigned variables and with shift counts that are compile
545                time constants
546 */
547 
548 #if (ALGORITHM_BYTE_ORDER == BRG_LITTLE_ENDIAN)
549 #define upr(x,n)        (((aes_32t)(x) << (8 * (n))) | ((aes_32t)(x) >> (32 - 8 * (n))))
550 #define ups(x,n)        ((aes_32t) (x) << (8 * (n)))
551 #define bval(x,n)       ((aes_08t)((x) >> (8 * (n))))
552 #define bytes2word(b0, b1, b2, b3)  \
553         (((aes_32t)(b3) << 24) | ((aes_32t)(b2) << 16) | ((aes_32t)(b1) << 8) | (b0))
554 #endif
555 
556 #if (ALGORITHM_BYTE_ORDER == BRG_BIG_ENDIAN)
557 #define upr(x,n)        (((aes_32t)(x) >> (8 * (n))) | ((aes_32t)(x) << (32 - 8 * (n))))
558 #define ups(x,n)        ((aes_32t) (x) >> (8 * (n))))
559 #define bval(x,n)       ((aes_08t)((x) >> (24 - 8 * (n))))
560 #define bytes2word(b0, b1, b2, b3)  \
561         (((aes_32t)(b0) << 24) | ((aes_32t)(b1) << 16) | ((aes_32t)(b2) << 8) | (b3))
562 #endif
563 
564 #if defined(SAFE_IO)
565 
566 #define word_in(x,c)    bytes2word(((aes_08t*)(x)+4*c)[0], ((aes_08t*)(x)+4*c)[1], \
567                                    ((aes_08t*)(x)+4*c)[2], ((aes_08t*)(x)+4*c)[3])
568 #define word_out(x,c,v) { ((aes_08t*)(x)+4*c)[0] = bval(v,0); ((aes_08t*)(x)+4*c)[1] = bval(v,1); \
569                           ((aes_08t*)(x)+4*c)[2] = bval(v,2); ((aes_08t*)(x)+4*c)[3] = bval(v,3); }
570 
571 #elif (ALGORITHM_BYTE_ORDER == PLATFORM_BYTE_ORDER)
572 
573 #define word_in(x,c)    (*((aes_32t*)(x)+(c)))
574 #define word_out(x,c,v) (*((aes_32t*)(x)+(c)) = (v))
575 
576 #else
577 
578 #define word_in(x,c)    aes_sw32(*((aes_32t*)(x)+(c)))
579 #define word_out(x,c,v) (*((aes_32t*)(x)+(c)) = aes_sw32(v))
580 
581 #endif
582 
583 /* the finite field modular polynomial and elements */
584 
585 #define WPOLY   0x011b
586 #define BPOLY     0x1b
587 
588 /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */
589 
590 #define m1  0x80808080
591 #define m2  0x7f7f7f7f
592 #define gf_mulx(x)  ((((x) & m2) << 1) ^ ((((x) & m1) >> 7) * BPOLY))
593 
594 /* The following defines provide alternative definitions of gf_mulx that might
595    give improved performance if a fast 32-bit multiply is not available. Note
596    that a temporary variable u needs to be defined where gf_mulx is used.
597 
598 #define gf_mulx(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6))
599 #define m4  (0x01010101 * BPOLY)
600 #define gf_mulx(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4)
601 */
602 
603 /* Work out which tables are needed for the different options   */
604 
605 #if defined( AES_ASM )
606 #if defined( ENC_ROUND )
607 #undef  ENC_ROUND
608 #endif
609 #define ENC_ROUND   FOUR_TABLES
610 #if defined( LAST_ENC_ROUND )
611 #undef  LAST_ENC_ROUND
612 #endif
613 #define LAST_ENC_ROUND  FOUR_TABLES
614 #if defined( DEC_ROUND )
615 #undef  DEC_ROUND
616 #endif
617 #define DEC_ROUND   FOUR_TABLES
618 #if defined( LAST_DEC_ROUND )
619 #undef  LAST_DEC_ROUND
620 #endif
621 #define LAST_DEC_ROUND  FOUR_TABLES
622 #if defined( KEY_SCHED )
623 #undef  KEY_SCHED
624 #define KEY_SCHED   FOUR_TABLES
625 #endif
626 #endif
627 
628 #if defined(ENCRYPTION) || defined(AES_ASM)
629 #if ENC_ROUND == ONE_TABLE
630 #define FT1_SET
631 #elif ENC_ROUND == FOUR_TABLES
632 #define FT4_SET
633 #else
634 #define SBX_SET
635 #endif
636 #if LAST_ENC_ROUND == ONE_TABLE
637 #define FL1_SET
638 #elif LAST_ENC_ROUND == FOUR_TABLES
639 #define FL4_SET
640 #elif !defined(SBX_SET)
641 #define SBX_SET
642 #endif
643 #endif
644 
645 #if defined(DECRYPTION) || defined(AES_ASM)
646 #if DEC_ROUND == ONE_TABLE
647 #define IT1_SET
648 #elif DEC_ROUND == FOUR_TABLES
649 #define IT4_SET
650 #else
651 #define ISB_SET
652 #endif
653 #if LAST_DEC_ROUND == ONE_TABLE
654 #define IL1_SET
655 #elif LAST_DEC_ROUND == FOUR_TABLES
656 #define IL4_SET
657 #elif !defined(ISB_SET)
658 #define ISB_SET
659 #endif
660 #endif
661 
662 #if defined(ENCRYPTION_KEY_SCHEDULE) || defined(DECRYPTION_KEY_SCHEDULE)
663 #if KEY_SCHED == ONE_TABLE
664 #define LS1_SET
665 #define IM1_SET
666 #elif KEY_SCHED == FOUR_TABLES
667 #define LS4_SET
668 #define IM4_SET
669 #elif !defined(SBX_SET)
670 #define SBX_SET
671 #endif
672 #endif
673 
674 /* generic definitions of Rijndael macros that use tables    */
675 
676 #define no_table(x,box,vf,rf,c) bytes2word( \
677     box[bval(vf(x,0,c),rf(0,c))], \
678     box[bval(vf(x,1,c),rf(1,c))], \
679     box[bval(vf(x,2,c),rf(2,c))], \
680     box[bval(vf(x,3,c),rf(3,c))])
681 
682 #define one_table(x,op,tab,vf,rf,c) \
683  (     tab[bval(vf(x,0,c),rf(0,c))] \
684   ^ op(tab[bval(vf(x,1,c),rf(1,c))],1) \
685   ^ op(tab[bval(vf(x,2,c),rf(2,c))],2) \
686   ^ op(tab[bval(vf(x,3,c),rf(3,c))],3))
687 
688 #define four_tables(x,tab,vf,rf,c) \
689  (  tab[0][bval(vf(x,0,c),rf(0,c))] \
690   ^ tab[1][bval(vf(x,1,c),rf(1,c))] \
691   ^ tab[2][bval(vf(x,2,c),rf(2,c))] \
692   ^ tab[3][bval(vf(x,3,c),rf(3,c))])
693 
694 #define vf1(x,r,c)  (x)
695 #define rf1(r,c)    (r)
696 #define rf2(r,c)    ((8+r-c)&3)
697 
698 /* perform forward and inverse column mix operation on four bytes in long word x in */
699 /* parallel. NOTE: x must be a simple variable, NOT an expression in these macros.  */
700 
701 #if defined(FM4_SET)    /* not currently used */
702 #define fwd_mcol(x)     four_tables(x,t_use(f,m),vf1,rf1,0)
703 #elif defined(FM1_SET)  /* not currently used */
704 #define fwd_mcol(x)     one_table(x,upr,t_use(f,m),vf1,rf1,0)
705 #else
706 #define dec_fmvars      aes_32t g2
707 #define fwd_mcol(x)     (g2 = gf_mulx(x), g2 ^ upr((x) ^ g2, 3) ^ upr((x), 2) ^ upr((x), 1))
708 #endif
709 
710 #if defined(IM4_SET)
711 #define inv_mcol(x)     four_tables(x,t_use(i,m),vf1,rf1,0)
712 #elif defined(IM1_SET)
713 #define inv_mcol(x)     one_table(x,upr,t_use(i,m),vf1,rf1,0)
714 #else
715 #define dec_imvars      aes_32t g2, g4, g9
716 #define inv_mcol(x)     (g2 = gf_mulx(x), g4 = gf_mulx(g2), g9 = (x) ^ gf_mulx(g4), g4 ^= g9, \
717                         (x) ^ g2 ^ g4 ^ upr(g2 ^ g9, 3) ^ upr(g4, 2) ^ upr(g9, 1))
718 #endif
719 
720 #if defined(FL4_SET)
721 #define ls_box(x,c)     four_tables(x,t_use(f,l),vf1,rf2,c)
722 #elif   defined(LS4_SET)
723 #define ls_box(x,c)     four_tables(x,t_use(l,s),vf1,rf2,c)
724 #elif defined(FL1_SET)
725 #define ls_box(x,c)     one_table(x,upr,t_use(f,l),vf1,rf2,c)
726 #elif defined(LS1_SET)
727 #define ls_box(x,c)     one_table(x,upr,t_use(l,s),vf1,rf2,c)
728 #else
729 #define ls_box(x,c)     no_table(x,t_use(s,box),vf1,rf2,c)
730 #endif
731 
732 #endif
733