-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
53 lines (46 loc) · 1.35 KB
/
index.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
45
46
47
48
49
50
51
52
53
const crypto = require('crypto');
const ALGORITHM = 'aes-256-cbc';
const BLOCK_SIZE = 16;
const ORIGINAL_ENCODING = 'utf8';
const ENCRYPTED_ENCODING = 'hex';
function getKey(secret) {
return crypto.createHash('sha256').update(secret).digest();
}
function generateIv() {
return crypto.randomBytes(BLOCK_SIZE);
}
function encrypt(key, json) {
try {
const str = JSON.stringify(json);
const ivBuffer = generateIv();
const cipher = crypto.createCipheriv(ALGORITHM, key, ivBuffer);
const encryptedStr = cipher.update(str, ORIGINAL_ENCODING, ENCRYPTED_ENCODING) + cipher.final(ENCRYPTED_ENCODING);
return {
iv: ivBuffer.toString(ENCRYPTED_ENCODING),
data: encryptedStr
};
} catch(e) {
const err = new Error('Error during encrypting');
err.internalError = e;
throw err;
}
}
function decrypt(key, {iv, data}) {
try {
const ivBuffer = Buffer.from(iv, ENCRYPTED_ENCODING);
const decipher = crypto.createDecipheriv(ALGORITHM, key, ivBuffer);
const decryptedStr = decipher.update(data, ENCRYPTED_ENCODING, ORIGINAL_ENCODING) + decipher.final(ORIGINAL_ENCODING);
return JSON.parse(decryptedStr);
} catch (e) {
const err = new Error('Error during decrypting');
err.internalError = e;
throw err;
}
}
module.exports = (secret) => {
const key = getKey(secret);
return {
encrypt: encrypt.bind(null, key),
decrypt: decrypt.bind(null, key)
};
};