Feel really good when everything is implemented right :) Or, at least,
there are no obvious bugs this time.
Dont't pay attention on the output routines, they're for testing purposes
only. I've tried to run the program on the test vectors and everything is
OK. Though I would appreciate comments on any subtle or obvious flaws that
may exist here. Great thanks for help!
Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZEOF(buf) (sizeof(buf)/sizeof(buf[0]))
typedef struct rc4_key
{
unsigned char state[256];
} rc4_key;
void swap (unsigned char *a, unsigned char *b)
{
unsigned char temp;
temp = *a;
*a = *b;
*b = temp;
}
void set_key (unsigned char *pass, size_t size, unsigned char *K, rc4_key
*key) {
unsigned char i, j;
short int counter;
unsigned char *S = &key->state[0];
for (counter = 0; counter < 256; counter++)
S [counter] = counter;
for (counter = 0; counter < 256; counter++)
K [counter] = pass [counter % size ];
i = j = 0;
for (counter = 0; counter < 256; counter++) /* initialize the S-box */
{
j = (j + S [counter] + K [i]) % 256;
swap (&S [counter], &S [j]);
i = (i + 1) % 256;
}
}
void rc4 (unsigned char *plain, size_t size, unsigned char *cipher,
rc4_key *key) {
unsigned char i, j;
short int counter;
unsigned char *S = &key->state[0];
unsigned char xor_index;
i = j = 0;
for(counter = 0; counter < size; counter ++) {
i = (i + 1) % 256;
j = (j + S [i]) % 256;
swap (&S [i], &S [j]);
xor_index = (S[i] + S[j]) % 256;
cipher [counter] = plain [counter] ^ S[xor_index];
}
}
int main()
{
unsigned char K [256];
unsigned char pass [] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
unsigned char plain [] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
unsigned char *cipher;
short int i;
struct rc4_key key;
set_key (pass, SIZEOF(pass), K, &key);
for (i = 0; i < 256; i++) /* nulify unneeded data */
K [i] = 0; /* so key will be not feasible to calculate */
memset (pass, 0x0, sizeof(pass)/sizeof(pass[0]));
printf("\nSize(plain): %d\n", SIZEOF(plain));
for (i = 0; i < SIZEOF(plain); i++)
printf ("%x ", plain [i]);
cipher = calloc (SIZEOF(plain), sizeof(plain[0]));
rc4 (plain, SIZEOF(plain), cipher, &key);
printf("\n\nSize(cipher): %d\n", SIZEOF(plain));
for (i = 0; i < SIZEOF(plain); i++)
printf ("%x ", cipher [i]);
free (cipher);
printf("\n\n");
return 0;
}
Received on Fri Dec 23 20:11:07 2005