Question

i have a sbox for an AES type implementation like

int   box[4][4] = {{0xA,0x3,0xC,0xB},
            {0xE,0xF,0x2,0xE},
            {0x6,0x4,0x0,0xF},
            {0xC,0x4,0xF,0x3}};

i want to get the first 2 bits and last 2 bits of a hexadecimal number and then replace it with the position in the sbox for example

  int x = 0xA //Because A has a binary representation from hex as 1010

then the row number would become the first 2 bits of A "10" and the column number would become the second 2 bits of A "10" therefore int x would go to the sbox and be replaced with "0xF"

how could i get the bits of A and use it to look up my sbox ?

Était-ce utile?

La solution

x = box[x & 3][(x >> 2) & 3]; will work assuming when you said "the row number would become the first 2 bits" you meant the two lower order bits of the four [i.e., the right two]; otherwise (when you said "first 2" you meant "left 2"), x = box[(x >> 2) & 3][x & 3]; is what you need.

In general, however, your 2 dimensional array accesses are slower than a 1 dimensional array access, so I would use a 1D array instead and not isolate the two pairs of bits as separate indexes. Instead use the low 4 bits of x as a 1D index. Then there won't be any extra shifting and masking or multiplication and addition of the 2D offset address calculation.

If "first 2 bits" meant "rightmost 2 bits"...

int box[16] = {0xA,0xE,0x6,0xC, 0x3,0xF,0x4,0x4, 0xC,0x2,0x0,0xF, 0xB,0xE,0xF,0x3};

If "first 2 bits" meant "leftmost 2 bits"...

int box[16] = {0xA,0x3,0xC,0xB, 0xE,0xF,0x2,0xE, 0x6,0x4,0x0,0xF, 0xC,0x4,0xF,0x3};

Then, to use the box...

x = box[x & 0xF];  // use the bottom 4 bits as single index

Hope that helps :-)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top