licensing update to APSL 2.0
[org.ibex.crypto.git] / src / org / ibex / crypto / RC4.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.crypto;
6
7
8 public class RC4 {
9     private final byte[] s = new byte[256];
10     private int x,y;
11     
12     public RC4(byte[] k) {
13         for(int i=0;i<256;i++) s[i] = (byte)i;
14         for(int i=0,j=0;i<256;i++) {
15             j = (j + (s[i]&0xff) + (k[i%k.length]&0xff))&0xff;
16             byte tmp = s[i];
17             s[i] = s[j];
18             s[j] = tmp;
19         }
20     }
21     
22     public void process(byte[] in, int ip, byte[] out, int op, int len) {
23         int x = this.x;
24         int y = this.y;
25         byte[] s = this.s;
26         for(int i=0;i<len;i++) {
27             x = (x + 1) & 0xff;
28             y = (y + (s[x]&0xff)) & 0xff;
29             byte tmp = s[x];
30             s[x] = s[y];
31             s[y] = tmp;
32             int t = ((s[x]&0xff) + (s[y]&0xff))&0xff;
33             int k = s[t];
34             out[op+i] = (byte)((in[ip+i]&0xff)^k);
35         }
36         this.x = x;
37         this.y = y;
38     }
39 }