Electronic – Smallest AES implementation for microcontrollers


Can anyone recommend a small, free implementation of AES-128 Rijndael for microcontrollers. Ideally, for the PIC18, though a general implementation in C would be useful.

Compiling the axTLS implementation for PIC18 and encrypting/decrypting a block requires 6KB ROM and 750b of RAM.

Compiling rijndael-alg-fst.c for PIC18 and encrypting/decrypting a block requires 28KB ROM and 0.5KB RAM.

Compiling Brian Gladman's 8-bit AES for PIC18 and encrypting/decrypting a block requires 19KB of ROM and 190 bytes of RAM.

Are there better optimised PIC specific variants available?

(updated RAM requirements for axTLS version)

Best Answer

I'm wondering how did you get 7.5kB of RAM usage with axTLS. Looking at the code, all the context is stored in this structure:

typedef struct aes_key_st 
    uint16_t rounds;
    uint16_t key_size;
    uint32_t ks[(AES_MAXROUNDS+1)*8];
    uint8_t iv[AES_IV_SIZE];

Size of this structure is 2 + 2 + 4 * 15 * 8 + 16 = 504. I see no global variables in aes.c, automatic variables are all small, so stack usage is also reasonable. So where does 7.5kB go? Perhaps you're trying to use the whole library instead of just extracting AES implementation from it?

Anyway, this implementation looks pretty simple, I'd rather stick to this code and try to optimize it. I know it can be tricky, but learning the AES details can help you at least to estimate the absolute minimum RAM usage.

Update: I've just tried to compile this library on IA-32 Linux and write a simple CBC AES-128 encryption test. Got the following results (first number is the section length hex):

 22 .data         00000028  0804a010  0804a010  00001010  2**2
                  CONTENTS, ALLOC, LOAD, DATA
 23 .bss          00000294  0804a040  0804a040  00001038  2**5

That's just 660 bytes of .bss (I've declared AES_CTX as a global variable). Most of .data is occupied by IV and key. I don't include .text here, as you'll get totally different result on PIC (data sections should be nearly the same size on both architectures).