(I know this is an old thread, but maybe my answer might help someone who reads it)
The problem is not RC4 code, but how you use it. What you need to understand, every time the encript method is called, the S array is changed to generate a pseudo-random key.
In this code, you are using the decript method after encript on the same instance of the RC4 class. But the RC4 class has a key creation in the constructor, so when you execute the decript method, the key is not created recently, because it was changed by the previous encript. Instead of this code:
int[] cipher = rc4.encrypt(text); //encryption System.out.print("\ncipher: "); for (int i = 0; i < cipher.length; i++) { System.out.print(cipher[i]); } int[] backtext = rc4.decrypt(cipher); //decryption System.out.print("\nback to text: "); for (int i = 0; i < backtext.length; i++) { System.out.print(backtext[i]); }
Use a new rc4 instance before decript:
int[] cipher = rc4.encrypt(text); //encryption System.out.print("\ncipher: "); for (int i = 0; i < cipher.length; i++) { System.out.print(cipher[i]); } rc4 = new RC4(keytest); int[] backtext = rc4.decrypt(cipher); //decryption System.out.print("\nback to text: "); for (int i = 0; i < backtext.length; i++) { System.out.print(backtext[i]); }
Thus, the decript method will have a pure S array, and it will be able to get the S-sequence in the same order as the previous encript method.
source share