Implementation error in the ARCFOUR cipher
molnarg opened this issue · 0 comments
molnarg commented
The RC4 cipher generates a constant byte as key stream after a while (~160 characters). The reason is that i
and j
are initialized to 0 every time arcfour_generate_stream()
is called, but they should be part of the global state initialized to 0 only once.
Pseudocode of RC4 PRG algorithm:
i := 0
j := 0
while GeneratingOutput:
i := (i + 1) mod 256
j := (j + S[i]) mod 256
swap values of S[i] and S[j]
K := S[(S[i] + S[j]) mod 256]
output K
endwhile
The implementation in this repo:
void arcfour_generate_stream(BYTE state[], BYTE out[], size_t len)
{
int i, j;
size_t idx;
BYTE t;
for (idx = 0, i = 0, j = 0; idx < len; ++idx) {
i = (i + 1) % 256;
j = (j + state[i]) % 256;
t = state[i];
state[i] = state[j];
state[j] = t;
out[idx] = state[(state[i] + state[j]) % 256];
}
}