| 1 | /********************************************************************* |
| 2 | * Filename: arcfour.c |
| 3 | * Author: Brad Conte (brad AT bradconte.com) |
| 4 | * Copyright: |
| 5 | * Disclaimer: This code is presented "as is" without any guarantees. |
| 6 | * Details: Implementation of the ARCFOUR encryption algorithm. |
| 7 | Algorithm specification can be found here: |
| 8 | * http://en.wikipedia.org/wiki/RC4 |
| 9 | *********************************************************************/ |
| 10 | |
| 11 | /*************************** HEADER FILES ***************************/ |
| 12 | #include <stdlib.h> |
| 13 | #include "arcfour.h" |
| 14 | |
| 15 | /*********************** FUNCTION DEFINITIONS ***********************/ |
| 16 | void arcfour_key_setup(BYTE state[], const BYTE key[], int len) |
| 17 | { |
| 18 | int i, j; |
| 19 | BYTE t; |
| 20 | |
| 21 | for (i = 0; i < 256; ++i) |
| 22 | state[i] = i; |
| 23 | for (i = 0, j = 0; i < 256; ++i) { |
| 24 | j = (j + state[i] + key[i % len]) % 256; |
| 25 | t = state[i]; |
| 26 | state[i] = state[j]; |
| 27 | state[j] = t; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // This does not hold state between calls. It always generates the |
| 32 | // stream starting from the first output byte. |
| 33 | void arcfour_generate_stream(BYTE state[], BYTE out[], size_t len) |
| 34 | { |
| 35 | int i, j; |
| 36 | size_t idx; |
| 37 | BYTE t; |
| 38 | |
| 39 | for (idx = 0, i = 0, j = 0; idx < len; ++idx) { |
| 40 | i = (i + 1) % 256; |
| 41 | j = (j + state[i]) % 256; |
| 42 | t = state[i]; |
| 43 | state[i] = state[j]; |
| 44 | state[j] = t; |
| 45 | out[idx] = state[(state[i] + state[j]) % 256]; |
| 46 | } |
| 47 | } |