I’m working on a simple (simple minded?) implementation of AES for learning purposes. I have made a small utility for generating the SBox table, but am having an odd infinite loop, which keeps spitting out the table ad infinitum. Below is the code in C that I’m trying to use. I just can’t seem to get it under control! I expected this to spit out 256 SBox values; it’s the same basic way that I (successfully) generated the log and anti-log tables.
The actual sbox()
function is implemented in an external file and is prototyped in the included header file. Note that I have successfully tested sbox()
to ensure that it returns the correct value for any given input; ok up to that point. Note that I am using unsigned char for in index variable type, as sbox()
expects that type.
I know I’m missing something simple, and will be embarrassed, but grateful once someone has shown me the error of my ways. 😉 Thanks in advance!
//mk_sbox.c
//output the sbox table
#include "gfmath.h"
int main() {
uchar i,e;
//display table
printf("sbox table:n");
for (i=0; i<256; i++) {
e=sbox(i);
printf("%hhu",e);
printf("%c",',');
}
printf("n");
return 0;
}
I’ve tried using while
instead of for
, but I get the same result. In case it matters here is the version of GCC:
$ gcc --version
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
I’m working in a GitHub Codespace.
2
Answers
Change
i
tounsigned int
.uchar
has the range0
..255
so it will never reach256
.The range of
unsigned char
type is[0, 255]
, wheni
is255
, incrementingi
(i++
) result in its value wrap around and its value becomes0
. In next iteration the loop conditioni < 256
result intrue
and loop continues.To solve this, either change the type of
i
tounsigned int
(as suggested in other post) or usedo..while
loop, like this:Additional –
You can combine these two statements
in one