Hi there I am trying to implement the RC4 algorithm in Java. I found this code as an example that help me to understand the idea:
public class RC4 {
privat
The Java code has a bug due to the use of the xor-swap technique:
S[i] ^= S[j];
S[j] ^= S[i];
S[i] ^= S[j];
Instead of this, you'll want to use a temp variable as in the below. I haven't delved into why the result isn't as expected with the xor swap, but I had decryption errors with this that were resolved by simply doing a straight-forward swap. I suspect it to be a subtle-side effect of the implicit cast from byte to int that occurs in order to do the xor operation.
public class RC4 {
private final byte[] S = new byte[256];
private final byte[] T = new byte[256];
private final int keylen;
public RC4(final byte[] key) {
if (key.length < 1 || key.length > 256) {
throw new IllegalArgumentException(
"key must be between 1 and 256 bytes");
} else {
keylen = key.length;
for (int i = 0; i < 256; i++) {
S[i] = (byte) i;
T[i] = key[i % keylen];
}
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + S[i] + T[i]) & 0xFF;
byte temp = S[i];
S[i] = S[j];
S[j] = temp;
}
}
}
public byte[] encrypt(final byte[] plaintext) {
final byte[] ciphertext = new byte[plaintext.length];
int i = 0, j = 0, k, t;
for (int counter = 0; counter < plaintext.length; counter++) {
i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
byte temp = S[i];
S[i] = S[j];
S[j] = temp;
t = (S[i] + S[j]) & 0xFF;
k = S[t];
ciphertext[counter] = (byte) (plaintext[counter] ^ k);
}
return ciphertext;
}
public byte[] decrypt(final byte[] ciphertext) {
return encrypt(ciphertext);
}
}