0

I have the follow code below to generate a scrambled state array, however, it does not seem to be generating the properly randomized state array for the key (51323).

unsigned char* generateStateArray(unsigned long key) {
    unsigned char s[256];
    //Load the state array from 1-255
    for (int i = 0; i < 256; i++) {
        s[i] = i;
    }

    //Get the binary representation of the key
    unsigned long n = key;

    int binary[64];
    for (int i = 0; i < 64; i++) {
        binary[i] = 0;
        std::cout << binary[i];
    }
    std::cout << std::endl;

    for (int i = 0; n > 0; i++) {
        binary[i] = n % 2;
        n /= 2;
    }

    //Randomize the entries
    int j = 0;

    for (int i = 0; i < 256; i++) {
        j = (j + binary[i % 64] + s[i]) & 255;

        char c = s[i];
        s[i] = s[j];
        s[j] = c;    
    }
}  

The output for S should look like:

Output

But it gives me this output:

my output

Any idea what I'm doing wrong and how I can fix it?

jww
  • 97,681
  • 90
  • 411
  • 885
Kaveen K
  • 33
  • 4
  • I *thought* RC4 discards the first several hundred bytes of the sequence to avoid a startup bias. Are you discarding the bytes? What test vectors are you using? – jww Nov 03 '19 at 03:56
  • @jww This is a very elementary school project, so I am not discarding any bytes. – Kaveen K Nov 03 '19 at 03:57
  • So you aren't implementing RC4, so the table in your book doesn't apply. – user207421 Nov 03 '19 at 04:07
  • The book gave the exact instructions for the RC4 cipher though – Kaveen K Nov 03 '19 at 04:34
  • 1
    The code only seems to implement the [initialization](https://en.wikipedia.org/wiki/RC4#Key-scheduling_algorithm_(KSA)) of the S-Boxes. The key `51323` may be encoded incorrectly into the `binary`-array. Is the encoding to be used described in more detail in the instructions? – Topaco Nov 03 '19 at 10:05
  • @jww: RC4 does *not* discard any bytes following the runup. That was simply an unofficial patch added after the fact in an attempt to fix some critical weaknesses. – President James K. Polk Nov 03 '19 at 14:51
  • FWIW, the key to RC4 is normally specified as an array of bytes. – 500 - Internal Server Error Nov 04 '19 at 10:17

0 Answers0