Commit | Line | Data |
---|---|---|
5d305aff DH |
1 | /* RC4 symmetric cipher encryption/decryption |
2 | * Copyright (c) 2006 by Ali Farhadi. | |
3 | * released under the terms of the Gnu Public License. | |
4 | * see the GPL for details. | |
5 | * | |
6 | * Email: ali[at]farhadi[dot]ir | |
7 | * Website: http://farhadi.ir/ | |
8 | */ | |
9 | ||
10 | /** | |
11 | * Encrypt given plain text using the key with RC4 algorithm. | |
12 | * All parameters and return value are in binary format. | |
13 | * | |
14 | * @param string key - secret key for encryption | |
15 | * @param string pt - plain text to be encrypted | |
16 | * @return string | |
17 | */ | |
18 | function rc4Encrypt(key, pt) { | |
19 | s = new Array(); | |
20 | for (var i=0; i<256; i++) { | |
21 | s[i] = i; | |
22 | } | |
23 | var j = 0; | |
24 | var x; | |
25 | for (i=0; i<256; i++) { | |
26 | j = (j + s[i] + key.charCodeAt(i % key.length)) % 256; | |
27 | x = s[i]; | |
28 | s[i] = s[j]; | |
29 | s[j] = x; | |
30 | } | |
31 | i = 0; | |
32 | j = 0; | |
33 | var ct = ''; | |
34 | for (var y=0; y<pt.length; y++) { | |
35 | i = (i + 1) % 256; | |
36 | j = (j + s[i]) % 256; | |
37 | x = s[i]; | |
38 | s[i] = s[j]; | |
39 | s[j] = x; | |
40 | ct += String.fromCharCode(pt.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]); | |
41 | } | |
42 | return ct; | |
43 | } | |
44 | ||
45 | /** | |
46 | * Decrypt given cipher text using the key with RC4 algorithm. | |
47 | * All parameters and return value are in binary format. | |
48 | * | |
49 | * @param string key - secret key for decryption | |
50 | * @param string ct - cipher text to be decrypted | |
51 | * @return string | |
52 | */ | |
53 | function rc4Decrypt(key, ct) { | |
54 | return rc4Encrypt(key, ct); | |
55 | } |