merge copyright headers with brians code
[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  * org.ibex.crypto.RC4 - By Brian Alliet
6  * Copyright (C) 2004 Brian Alliet
7  */
8
9 package org.ibex.crypto;
10
11 public class RC4 implements Cipher {
12     private final byte[] s = new byte[256];
13     private int x,y;
14     
15     public RC4(byte[] k) {
16         for(int i=0;i<256;i++) s[i] = (byte)i;
17         for(int i=0,j=0;i<256;i++) {
18             j = (j + (s[i]&0xff) + (k[i%k.length]&0xff))&0xff;
19             byte tmp = s[i];
20             s[i] = s[j];
21             s[j] = tmp;
22         }
23     }
24     
25     public void process(byte[] in, int ip, byte[] out, int op, int len) {
26         int x = this.x;
27         int y = this.y;
28         byte[] s = this.s;
29         for(int i=0;i<len;i++) {
30             x = (x + 1) & 0xff;
31             y = (y + (s[x]&0xff)) & 0xff;
32             byte tmp = s[x];
33             s[x] = s[y];
34             s[y] = tmp;
35             int t = ((s[x]&0xff) + (s[y]&0xff))&0xff;
36             int k = s[t];
37             out[op+i] = (byte)((in[ip+i]&0xff)^k);
38         }
39         this.x = x;
40         this.y = y;
41     }
42 }