8891ec7d0bb5193a67cf1b1466c7d04f5810e3de
[org.ibex.crypto.git] / src / org / ibex / crypto / RC4.java
1 package org.ibex.crypto;
2
3 package org.ibex.crypto;
4
5 public class RC4 implements Cipher {
6     private final byte[] s = new byte[256];
7     private int x,y;
8     
9     public RC4(byte[] k) {
10         for(int i=0;i<256;i++) s[i] = (byte)i;
11         for(int i=0,j=0;i<256;i++) {
12             j = (j + (s[i]&0xff) + (k[i%k.length]&0xff))&0xff;
13             byte tmp = s[i];
14             s[i] = s[j];
15             s[j] = tmp;
16         }
17     }
18     
19     public void process(byte[] in, int ip, byte[] out, int op, int len) {
20         int x = this.x;
21         int y = this.y;
22         byte[] s = this.s;
23         for(int i=0;i<len;i++) {
24             x = (x + 1) & 0xff;
25             y = (y + (s[x]&0xff)) & 0xff;
26             byte tmp = s[x];
27             s[x] = s[y];
28             s[y] = tmp;
29             int t = ((s[x]&0xff) + (s[y]&0xff))&0xff;
30             int k = s[t];
31             out[op+i] = (byte)((in[ip+i]&0xff)^k);
32         }
33         this.x = x;
34         this.y = y;
35     }
36 }