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