void rc4_set_key(RC4_CTX *ctx, unsigned char *key, int key_len) { int i = 0; unsigned char x = 0, y = 0; unsigned char *S = ctx->S; ctx->x = x = 0; ctx->y = y = 0; for (i = 0; i < 256; i++) { S[i] = (unsigned char)i; } for (i = 0; i < 256; i++) { y = (y + S[i] + key[x]) & 0xff; rc4_swap(&S[i], &S[y]); if (++x >= key_len) { x = 0; } } }
void rc4_encrypt(RC4_CTX *ctx, uint8_t *buffer, size_t length) { for (size_t idx = 0; idx < length; idx++) { ctx->i++; ctx->j += ctx->S[ctx->i]; rc4_swap(ctx, ctx->i, ctx->j); uint8_t K = ctx->S[(ctx->S[ctx->i] + ctx->S[ctx->j]) % 256]; buffer[idx] ^= K; } }
void rc4_init(RC4_CTX *ctx, const uint8_t *key, size_t length) { ctx->i = 0; ctx->j = 0; for (size_t i = 0; i < 256; i++) { ctx->S[i] = i; } uint8_t j = 0; for (size_t i = 0; i < 256; i++) { j += ctx->S[i] + key[i % length]; rc4_swap(ctx, i, j); } }
void rc4_transform(rc4_sbox_t *rc4_sbox, unsigned char *buffer_ptr, unsigned int buffer_len) { unsigned int i; for(i = 0; i < buffer_len; i ++) { // The pseudo-random generation algorithm rc4_sbox->x = (rc4_sbox->x + 1) & 0xff; rc4_sbox->y = (rc4_sbox->y + rc4_sbox->state[rc4_sbox->x]) & 0xff; rc4_swap(rc4_sbox->state[rc4_sbox->x], rc4_sbox->state[rc4_sbox->y]); unsigned char keyChar = rc4_sbox->state[(rc4_sbox->state[rc4_sbox->x] + rc4_sbox->state[rc4_sbox->y]) & 0xff]; if(buffer_ptr) // NULL when seeking buffer_ptr[i] ^= keyChar; } }
void rc4_crypt(RC4_CTX *ctx, unsigned char *data, int data_len) { int i = 0; unsigned char x = 0, y = 0; unsigned char *S = ctx->S; for (i = 0; i < data_len; i++) { x = (x + 1) & 0xff; y = (y + S[x]) & 0xff; rc4_swap(&S[x], &S[y]); data[i] ^= S[(S[x] + S[y]) & 0xff]; } ctx->x = x; ctx->y = y; }
void rc4_init(rc4_sbox_t *rc4_sbox, const unsigned char *key_ptr, unsigned int key_len) { rc4_sbox->x = 0; rc4_sbox->y = 0; // Initialisation of the permutation unsigned int i; for(i = 0; i < 256; i++) rc4_sbox->state[i] = (char)i; // Mixing permutation unsigned int j = 0; unsigned int k; for(i = 0; i < 256; i++) { k = i % key_len; j = (key_ptr[k] + rc4_sbox->state[i] + j) & 0xff; rc4_swap(rc4_sbox->state[i], rc4_sbox->state[j]); } }