-
Notifications
You must be signed in to change notification settings - Fork 62
/
encryption.js
44 lines (31 loc) · 999 Bytes
/
encryption.js
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
var crypto = require('crypto');
function KeyStream(key, drop) {
this.cipher = crypto.createCipheriv('rc4', key, new Buffer(''));
this.key = key;
drop = drop || 256;
var buffer = new Buffer(drop);
for(var i = 0; i < drop; i++) {
buffer.writeUInt8(i, i);
}
this.cipher.update(buffer);
}
KeyStream.prototype.encode = function(data, append) {
if(append !== false) {
append = true;
}
var hash = this.cipher.update(data),
hmac = crypto.createHmac('sha1', this.key).update(hash).digest(),
affix = hmac.slice(0, 4);
var buffers = append ? [hash, affix] : [affix, hash];
return Buffer.concat(buffers, affix.length + hash.length);
};
KeyStream.prototype.decode = function(data) {
return this.cipher.update(data.slice(4)).slice();
};
function pbkdf2(password, salt, iterations, length) {
iterations = iterations || 16;
length = length || 20;
return crypto.pbkdf2Sync(password, salt, iterations, length);
}
exports.KeyStream = KeyStream;
exports.pbkdf2 = pbkdf2;