用C语言实现AES算法
#include
#include
#ifndef uint8
#define uint8 unsigned char
#endif
#ifndef uint32
#define uint32 unsigned long int
#endif
typedef struct
{
uint32 erk[64]; /* encryption round keys */
uint32 drk[64]; /* decryption round keys */
int nr; /* number of rounds */
}
aes_context;
//#define TEST
/* uncomment the following line to use pre-computed tables */
/* otherwise the tables will be generated at the first run */
/* #define FIXED_TABLES */
#ifndef FIXED_TABLES
/* forward S-box & tables */
uint32 FSb[256];
uint32 FT0[256];
uint32 FT1[256];
uint32 FT2[256];
uint32 FT3[256];
/* reverse S-box & tables */
uint32 RSb[256];
uint32 RT0[256];
uint32 RT1[256];
uint32 RT2[256];
uint32 RT3[256];
/* round constants */
uint32 RCON[10];
/* tables generation flag */
int do_init = 1;
/* tables generation routine */
#define ROTR8(x) ( ( ( x << 24 ) & 0xFFFFFFFF ) | \
( ( x & 0xFFFFFFFF ) >> 8 ) )
#define XTIME(x) ( ( x << 1 ) ^ ( ( x & 0x80 ) ? 0x1B : 0x00 ) )
#define MUL(x,y) ( ( x && y ) ? pow[(log[x] + log[y]) % 255] : 0 )
void aes_gen_tables( void )
{
int i;
uint8 x, y;
uint8 pow[256];
uint8 log[256];
/* compute pow and log tables over GF(2^8) */
for( i = 0, x = 1; i < 256; i++, x ^= XTIME( x ) )
{
pow[i] = x;
log[x] = i;
}
/* calculate the round constants */
for( i = 0, x = 1; i < 10; i++, x = XTIME( x ) )
{
RCON[i] = (uint32) x << 24;
}
/* generate the forward and reverse S-boxes */
FSb[0x00] = 0x63;
RSb[0x63] = 0x00;
for( i = 1; i < 256; i++ )
{
x = pow[255 - log[i]];
y = x; y = ( y << 1 ) | ( y >> 7 );
x ^= y; y = ( y << 1 ) | ( y >> 7 );
x ^= y; y = ( y << 1 ) | ( y >> 7 );
x ^= y; y = ( y << 1 ) | ( y >> 7 );
x ^= y ^ 0x63;
FSb[i] = x;
RSb[x] = i;
}
/* generate the forward and reverse tables */
for( i = 0; i < 256; i++ )
{
x = (unsigned char) FSb[i]; y = XTIME( x );
FT0[i] = (uint32) ( x ^ y ) ^
( (uint32) x << 8 ) ^
( (uint32) x << 16 ) ^
( (uint32) y << 24 );
FT0[i] &= 0xFFFFFFFF;
FT1[i] = ROTR8( FT0[i] );
FT2[i] = ROTR8( FT1[i] );
FT3[i] = ROTR8( FT2[i] );
y = (unsigned char) RSb[i];
RT0[i] = ( (uint32) MUL( 0x0B, y ) ) ^
( (uint32) MUL( 0x0D, y ) << 8 ) ^
( (uint32) MUL( 0x09, y ) << 16 ) ^
( (uint32) MUL( 0x0E, y ) << 24 );
RT0[i] &= 0xFFFFFFFF;
RT1[i] = ROTR8( RT0[i] );
RT2[i] = ROTR8( RT1[i] );
R
T3[i] = ROTR8( RT2[i] );
}
}
#else
/* forward S-box */
static const uint32 FSb[256] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0