Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fixed RC4 to preserve state across calls
  • Loading branch information
lcn2 committed May 31, 2017
commit a5e74768328e3573d5f2ef0a76124b863a9df8e2
12 changes: 8 additions & 4 deletions arcfour.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,19 @@ void arcfour_key_setup(BYTE state[], const BYTE key[], int len)
state[i] = state[j];
state[j] = t;
}
state[ARCFOUR_I] = 0;
state[ARCFOUR_J] = 0;
}

// This does not hold state between calls. It always generates the
// stream starting from the first output byte.
void arcfour_generate_stream(BYTE state[], BYTE out[], size_t len)
{
int i = 0;
int j = 0;
int i;
int j;
size_t idx;
BYTE t;

i = state[ARCFOUR_I];
j = state[ARCFOUR_J];
for (idx = 0; idx < len; ++idx) {
i = (i + 1) % 256;
j = (j + state[i]) % 256;
Expand All @@ -45,4 +47,6 @@ void arcfour_generate_stream(BYTE state[], BYTE out[], size_t len)
state[j] = t;
out[idx] = state[(state[i] + state[j]) % 256];
}
state[ARCFOUR_I] = i;
state[ARCFOUR_J] = j;
}
7 changes: 7 additions & 0 deletions arcfour.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,11 @@ void arcfour_key_setup(BYTE state[], const BYTE key[], int len);
// len - number of bytes to generate
void arcfour_generate_stream(BYTE state[], BYTE out[], size_t len);

#if !defined(ARCFOUR_I)
# define ARCFOUR_I (256)
#endif
#if !defined(ARCFOUR_J)
# define ARCFOUR_J (257)
#endif

#endif // ARCFOUR_H
2 changes: 1 addition & 1 deletion arcfour_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
/*********************** FUNCTION DEFINITIONS ***********************/
int rc4_test()
{
BYTE state[256];
BYTE state[256+2];
BYTE key[3][10] = {{"Key"}, {"Wiki"}, {"Secret"}};
BYTE stream[3][10] = {{0xEB,0x9F,0x77,0x81,0xB7,0x34,0xCA,0x72,0xA7,0x19},
{0x60,0x44,0xdb,0x6d,0x41,0xb7},
Expand Down