0

This is the RC4 encryption and decryption code in a java file, I got this from the answer of this post RC4 encryption java:

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;
            byte tmp;
            for (int i = 0; i < 256; i++) {
                j = (j + S[i] + T[i]) & 0xFF;
                tmp = S[j];
                S[j] = S[i];
                S[i] = tmp;
            }
        }
    }

    public byte[] encrypt(final byte[] plaintext) {
        final byte[] ciphertext = new byte[plaintext.length];
        int i = 0, j = 0, k, t;
        byte tmp;
        for (int counter = 0; counter < plaintext.length; counter++) {
            i = (i + 1) & 0xFF;
            j = (j + S[i]) & 0xFF;
            tmp = S[j];
            S[j] = S[i];
            S[i] = tmp;
            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);
    }
}

I tried to do this in another java file in the main method, the encryption works, but the decryption is not working, but I couldn't get out the plaintext:

        String key = "key";
        String ptStr = "hello";
        RC4 rc41 = new RC4(key.getBytes());
        byte[] ct = rc41.encrypt(ptStr.getBytes());
        byte[] pt = rc41.decrypt(ct);
        System.out.println(new String(pt));

The output of the print is this: êGE

Astoach167
  • 91
  • 1
  • 7
  • 1
    Why are you rolling your own RC4 implementation, why not just use the one built-in in Java? I'm not sure if you'll find someone willing to scrutinize your code to see what you're doing wrong. – Mark Rotteveel Jul 30 '20 at 09:30
  • Oh, I know I can just use the built-in but I am curious, I just want to know whats wrong with it, because its exactly the same as the answer in the post – Astoach167 Jul 30 '20 at 09:39
  • You'll have to reset/recreate the `RC4` in between. The internal S-boxes are all messed up from the encrypting, if you try to decrypt with the same one, it can't reverse the encryption. – Kayaman Jul 30 '20 at 09:41

0 Answers0