Article Index

9°) implémentation C89

#include <stdio.h>

typedef struct rc4_key
{
    unsigned char state[256];
    unsigned char x, y;
} rc4_key;

static void swap_byte(unsigned char *a, unsigned char *b)
{
    unsigned char swapByte = *a;
    *a = *b;
    *b = swapByte;
}

void prepare_key(unsigned char *key, int size, rc4_key *k)
{
    unsigned char x, y;
    unsigned char *state;
    short i;

    state = &k->state[0];
    k->x = k->y = x = y = 0;

    for(i = 0; i < 256; i++)
        state[i] = i;

    for(i = 0; i < 256; i++)
    {
        y = key[x] + state[i] + y;
        swap_byte(&state[i], &state[y]);
        x = (x + 1) % size;
    }
}

void rc4(unsigned char *data, int count, rc4_key *k, int offset)
{
    unsigned char x, y, idx;
    unsigned char* state;
    short i;

    x = k->x;
    y = k->y;

    state = &k->state[0];

    for(i = 0; i < offset; ++i)
    {
        x++;
        y = state[x] + y;
        swap_byte(&state[x], &state[y]);
    }

    for(i = 0; i<count; ++i)
    {
        x++;
        y = state[x] + y;
        swap_byte(&state[x], &state[y]);
        idx = state[x] + state[y];
        data[i] ^= state[idx];
    }

    k->x = x;
    k->y = y;
}

int main(int argc, const char **argv)
{
    short i;
    rc4_key info;

    unsigned char key[] = "WEP";
    unsigned char message[] = "info528";

    prepare_key(key, 3, &info);
    rc4(message, 7, &info, 1234);

    for(i = 0; i<7; ++i)
        printf("%02X", message[i]);
    printf("\n");
}