java RC4加密及解密

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);
    }
    
    public static void main(String[] args) throws Exception {
        byte[] key = {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
        };

        String text = "12345"; // text as 12345

        RC4 rc4_encode = new RC4(key);
        RC4 rc4_decode = new RC4(key);

        System.out.print("\noriginal text: ");
        System.out.print(text);

        byte[] cipher = rc4_encode.encrypt(text.getBytes()); //encryption
        System.out.print("\ncipher: ");
        for (int i = 0; i < cipher.length; i++) {
            System.out.printf("%02X", cipher[i]);
        }

        byte[] backtext = rc4_decode.decrypt(cipher); //decryption
        System.out.print("\nplain text: ");
        System.out.print(new String(backtext));
    }
}

 

你可能感兴趣的:(java RC4加密及解密)