MARC4.js
1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
(function(){
var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto;
// Shortcuts
var util = C.util,
charenc = C.charenc,
UTF8 = charenc.UTF8,
Binary = charenc.Binary;
var MARC4 = C.MARC4 = {
/**
* Public API
*/
encrypt: function (message, password) {
var
// Convert to bytes
m = UTF8.stringToBytes(message),
// Generate random IV
iv = util.randomBytes(16),
// Generate key
k = password.constructor == String ?
// Derive key from passphrase
C.PBKDF2(password, iv, 32, { asBytes: true }) :
// else, assume byte array representing cryptographic key
password;
// Encrypt
MARC4._marc4(m, k, 1536);
// Return ciphertext
return util.bytesToBase64(iv.concat(m));
},
decrypt: function (ciphertext, password) {
var
// Convert to bytes
c = util.base64ToBytes(ciphertext),
// Separate IV and message
iv = c.splice(0, 16),
// Generate key
k = password.constructor == String ?
// Derive key from passphrase
C.PBKDF2(password, iv, 32, { asBytes: true }) :
// else, assume byte array representing cryptographic key
password;
// Decrypt
MARC4._marc4(c, k, 1536);
// Return plaintext
return UTF8.bytesToString(c);
},
/**
* Internal methods
*/
// The core
_marc4: function (m, k, drop) {
// State variables
var i, j, s, temp;
// Key setup
for (i = 0, s = []; i < 256; i++) s[i] = i;
for (i = 0, j = 0; i < 256; i++) {
j = (j + s[i] + k[i % k.length]) % 256;
// Swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
// Clear counters
i = j = 0;
// Encryption
for (var k = -drop; k < m.length; k++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
// Swap
temp = s[i];
s[i] = s[j];
s[j] = temp;
// Stop here if we're still dropping keystream
if (k < 0) continue;
// Encrypt
m[k] ^= s[(s[i] + s[j]) % 256];
}
}
};
})();