RC 4対称暗号化

10524 ワード

public class RC4 {
    byte[] s = new byte[256];
    byte[] key;
    byte keylen;// 4 ~ 16
    int pi = 0;
    int pj = 0;

    public RC4() {
        this.keylen = 16;
        randKey();
        ksa();
    }

    public RC4(byte keylen) {
        this.keylen = keylen;
        randKey();
        ksa();
    }

    public RC4(byte[] key) {
        this.key = key;
        keylen = (byte) key.length;
        ksa();
    }

    private void randKey() {
//        SecureRandom r = new SecureRandom("abc".getBytes());
        Random r = new Random(0xdeadbeef);
        key = new byte[keylen];
        r.nextBytes(key);
    }

    public byte[] getKey() {
        return key;
    }

    private void ksa() {
        for (int i = 0; i < s.length; i++) {
            s[i] = (byte) i;
        }
        int j = 0;
        for (int i = 0; i < s.length; i++) {                    // s 
            j = ((j + s[i] & 0xff + key[i % keylen] & 0xff) % 256);    // 

            byte tmp = s[i];                                    // 
            s[i] = s[j];
            s[j] = tmp;
        }
    }

    public byte prgaOneByte(byte in) {
        pi = pi + 1 % 256;
        pj = (pj + s[pi] & 0xff);

        byte tmp = s[pi];
        s[pi] = s[pj];
        s[pj] = tmp;

        int t = (s[pi] & 0xff + s[pj] & 0xff) % 256;
        int k = s[t] & 0xff;
        return (byte) ((k ^ in & 0xff) & 0xff);
    }


    public void prga(InputStream is, OutputStream os) throws IOException {
        int bufsize = 4 * 1024;
        byte[] buffer = new byte[bufsize]; // 4K
        byte[] outBuffer;
        int len = 0;
        while ((len = is.read(buffer, 0, bufsize)) != -1) { // 
            outBuffer = prga(buffer, 0, len);
            os.write(outBuffer);
        }
    }

    public byte[] prga(byte[] buffer, int off, int len) throws IOException {
        byte[] outBuffer = new byte[buffer.length]; // 4K
        for (int i = 0 + off; i < len; i++) {                    // 
            outBuffer[i] = prgaOneByte(buffer[i]);
        }
        return outBuffer;
    }

    public static void main(String[] args) throws IOException {
        String msg = "hello wold!";
        byte[] bmsg = msg.getBytes();
        byte[] key;
        System.out.println("bmsg :" + Arrays.toString(bmsg));   // 

        RC4 rc4 = new RC4();
        key = rc4.getKey();
        byte[] ebmsg = rc4.prga(bmsg, 0, bmsg.length);
        System.out.println("ebmsg :" + Arrays.toString(ebmsg)); // 

        RC4 rc42 = new RC4(key);
        byte[] debmsg = rc42.prga(ebmsg, 0, ebmsg.length);
        System.out.println("debmsg:" + Arrays.toString(debmsg));// 
        System.out.println("debmsg:" + new String(debmsg));
    }
}

 
しゅつりょく
bmsg :[104, 101, 108, 108, 111, 32, 119, 111, 108, 100, 33]
ebmsg :[-76, 34, -32, -95, -127, 85, -93, -16, -126, 110, -56]
debmsg:[104, 101, 108, 108, 111, 32, 119, 111, 108, 100, 33]
debmsg:hello wold!