skip to Main Content

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


  1. Change i to unsigned int. uchar has the range 0..255 so it will never reach 256.

    Login or Signup to reply.
  2. The range of unsigned char type is [0, 255], when i is 255, incrementing i (i++) result in its value wrap around and its value becomes 0. In next iteration the loop condition i < 256 result in true and loop continues.

    To solve this, either change the type of i to unsigned int (as suggested in other post) or use do..while loop, like this:

        unsigned char i = 0;
        do {
            // loop body
        } while (i++ < 255);
    

    Additional –

    You can combine these two statements

            printf("%hhu",e);
            printf("%c",',');
    

    in one

            printf("%hhu,",e);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search