Re: (long) An AES implementation for 32-bit platforms

From: Tom St Denis (tomstdenis_at_iahu.ca)
Date: 06/10/03


Date: Tue, 10 Jun 2003 19:16:47 GMT

Mok-Kong Shen wrote:
> Recently in discussions in another thread I suggested
> that unions are well suited for byte-array implementations
> of AES. For with a definition like
>
> union BLOCK
> { byte b[16];
> byte bm[4][4];
> word w[4];
> };
> BLOCK yy,zz;

Two words: "Packing Order".

Consider the trivial union

union B {
    byte a[2];
    word c;
};

Where ||c|| == 2 * ||a||.

What is the value of B.c after

union B T;
T.a[0] = 0xFF;
T.a[1] = 0x12;

Hint: There are two valid answers.

The problem is unions were not meant for this [though it can be used for
it]. A lot of people think this way but it honestly isn't true.

For example, consider a compile which aligns elements in say

union B {
    byte a[2];
    long c;
};

Where ||c|| == 4 * ||a||.

So the compiler may align a to the upper or lower half of c. All that
is required is that (B.a[x] = y) == y, be true for 0 <= x < 2, and a y
that is in range.

An example of portable usage of a union would be, for example, the
descriptor tables in LibTomCrypt. I put multiple structures in the same
union but only access *one* of them at a given time. So for the
purposes of a given algorithm all the other elements of the union might
as well not exist. I use the union so I can put multiple data types in
a collection and not waste space.

In the end the trick may work on your compiler, but it is perfectly
valid for it not to work on another compiler even for the same platform!
  So its a risky [and not very profitable] move to take.

Tom



Relevant Pages