rc4加密

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class RC4 {
    public static void main(String[] args) {
        String msg = "abcd";
        String key = "Tester1234";
        byte[] buf = null;
        try {
            buf = msg.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {

        }
        byte[] jiami = RC4.rc4(key, buf);

        String jiamimsg = "";
        try {
            jiamimsg = new String(jiami, "UTF-8");
            System.out.println(jiamimsg);
        } catch (UnsupportedEncodingException e) {

        }
        System.out.println(Base64.encodeBase64String(jiami));

        byte[] jiemi = RC4.rc4(key, jiami);
        String jiemimsg = "";
        try {
            jiemimsg = new String(jiemi, "UTF-8");
            System.out.println(jiemimsg);
        } catch (UnsupportedEncodingException e) {

        }

    }

    private static byte[] rc4(String key, byte[] buf) {
        int[] box = new int[256];
        byte[] k = key.getBytes();
        int i = 0;
        int x = 0;
        int t = 0;
        int l = k.length;

        for (i = 0; i < 256; i++) {
            box[i] = i;
        }

        for (i = 0; i < 256; i++) {
            x = (x + box[i] + k[(i % l)]) % 256;

            t = box[x];
            box[x] = box[i];
            box[i] = t;
        }

        t = 0;
        i = 0;
        l = buf.length;
        int o = 0;
        int j = 0;
        byte[] out = new byte[l];
        int[] ibox = new int[256];
        System.arraycopy(box, 0, ibox, 0, 256);

        for (int c = 0; c < l; c++) {
            i = (i + 1) % 256;
            j = (j + ibox[i]) % 256;

            t = ibox[j];
            ibox[j] = ibox[i];
            ibox[i] = t;

            o = ibox[((ibox[i] + ibox[j]) % 256)];
            out[c] = ((byte) (buf[c] ^ o));
        }
        return out;
    }

}
原文地址:https://www.cnblogs.com/tonggc1668/p/6434401.html