Created
January 16, 2014 07:48
-
-
Save songzhiyong/8451195 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
S[i] ^= S[j]; | |
S[j] ^= S[i]; | |
S[i] ^= S[j]; | |
} | |
} | |
} | |
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; | |
S[i] ^= S[j]; | |
S[j] ^= S[i]; | |
S[i] ^= S[j]; | |
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); | |
} | |
} |
There are differences for other inputs and keys as well.
Someone fixed your implementation: https://stackoverflow.com/questions/12289717/rc4-encryption-java.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For input test 'input' and key 'key' your implementation gives: 6202449874, but online tools like https://cryptii.com/pipes/rc4-encryption or http://rc4.online-domain-tools.com/ generate: 6202449850. Last byte is different.