Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
9103 anupam.sin 1
package in.shop2020.serving.utils.ebs;
2
 
3
/**
4
 * This class enciphers or deciphers strings using the RC4 encryption algorithm.
5
 * 
6
 * @author R. Prince - Java coded based on the original VB source by Mike
7
 *         Shaffer
8
 **/
9
public class RC4 {
10
	private byte state[] = new byte[256];
11
	private int x;
12
	private int y;
13
 
14
	/**
15
	 * Initializes the class with a string key. The length of a normal key
16
	 * should be between 1 and 2048 bits. But this method doens't check the
17
	 * length at all.
18
	 * 
19
	 * @param key
20
	 *            the encryption/decryption key
21
	 */
22
	public RC4(String key) throws NullPointerException {
23
		this(key.getBytes());
24
	}
25
 
26
	/**
27
	 * Initializes the class with a byte array key. The length of a normal key
28
	 * should be between 1 and 2048 bits. But this method doens't check the
29
	 * length at all.
30
	 * 
31
	 * @param key
32
	 *            the encryption/decryption key
33
	 */
34
	public RC4(byte[] key) throws NullPointerException {
35
 
36
		for (int i = 0; i < 256; i++) {
37
			state[i] = (byte) i;
38
		}
39
 
40
		x = 0;
41
		y = 0;
42
 
43
		int index1 = 0;
44
		int index2 = 0;
45
 
46
		byte tmp;
47
 
48
		if (key == null || key.length == 0) {
49
			throw new NullPointerException();
50
		}
51
 
52
		for (int i = 0; i < 256; i++) {
53
 
54
			index2 = ((key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
55
 
56
			tmp = state[i];
57
			state[i] = state[index2];
58
			state[index2] = tmp;
59
 
60
			index1 = (index1 + 1) % key.length;
61
		}
62
 
63
	}
64
 
65
	/**
66
	 * RC4 encryption/decryption.
67
	 * 
68
	 * @param data
69
	 *            the data to be encrypted/decrypted
70
	 * @return the result of the encryption/decryption
71
	 */
72
	public byte[] rc4(String data) {
73
		if (data == null) {
74
			return null;
75
		}
76
 
77
		byte[] tmp = data.getBytes();
78
 
79
		this.rc4(tmp);
80
 
81
		return tmp;
82
	}
83
 
84
	/**
85
	 * RC4 encryption/decryption.
86
	 * 
87
	 * @param buf
88
	 *            the data to be encrypted/decrypted
89
	 * @return the result of the encryption/decryption
90
	 */
91
	public byte[] rc4(byte[] buf) {
92
		// int lx = this.x;
93
		// int ly = this.y;
94
 
95
		int xorIndex;
96
		byte tmp;
97
 
98
		if (buf == null) {
99
			return null;
100
		}
101
 
102
		byte[] result = new byte[buf.length];
103
 
104
		for (int i = 0; i < buf.length; i++) {
105
 
106
			x = (x + 1) & 0xff;
107
			y = ((state[x] & 0xff) + y) & 0xff;
108
 
109
			tmp = state[x];
110
			state[x] = state[y];
111
			state[y] = tmp;
112
 
113
			xorIndex = ((state[x] & 0xff) + (state[y] & 0xff)) & 0xff;
114
			result[i] = (byte) (buf[i] ^ state[xorIndex]);
115
		}
116
 
117
		// this.x = lx;
118
		// this.y = ly;
119
 
120
		return result;
121
	}
122
 
123
}