-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
80 lines (63 loc) · 2.47 KB
/
lib.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
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
const querystring = require('querystring');
const crypto = require('crypto');
const createCipher = require('./create-cipher');
const ALGORITHM = 'aes256';
const PLAINTEXTENCODING = 'utf8';
const CIPHERTEXTENCODING = 'hex';
const DELIMITER = '|';
const ENCRYPTEDKEY = 'enc';
function encrypt(plaintext, encryptionKey){
let [key, iv] = createCipher(ALGORITHM, encryptionKey);
key = Buffer.from(`${key}`, 'hex');
iv = Buffer.from(`${iv}`, 'hex');
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
return cipher.update(plaintext, PLAINTEXTENCODING, CIPHERTEXTENCODING) + cipher.final(CIPHERTEXTENCODING);
}
function decrypt(ciphertext, encryptionKey){
let [key, iv] = createCipher(ALGORITHM, encryptionKey);
key = Buffer.from(`${key}`, 'hex');
iv = Buffer.from(`${iv}`, 'hex');
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
return decipher.update(ciphertext, CIPHERTEXTENCODING, PLAINTEXTENCODING) + decipher.final(PLAINTEXTENCODING);
}
function obfuscate(s, options){
if (!options){
throw new Error('options undefined');
}
const allKeys = querystring.parse(s);
const obfuscatedKeys = options.obfuscate.reduce((prev, key)=>{
if (allKeys[key]){
prev = prev || {};
prev[key]=allKeys[key];
delete allKeys[key];
}
return prev;
}, undefined);
if (obfuscatedKeys){
allKeys[ENCRYPTEDKEY] = options.encryptionKey.name + DELIMITER + encrypt(querystring.stringify(obfuscatedKeys), options.encryptionKey.value)
}
return querystring.unescape(querystring.stringify(allKeys));
}
function clarify(s, options){
if (!options){
throw new Error('options undefined');
}
const allKeys = querystring.parse(s);
const encrypted = allKeys[ENCRYPTEDKEY];
if (encrypted){
// get the encryption key
const encryptionKeyName = encrypted.split('|')[0];
const encryptionKey = options.encryptionKeys[encryptionKeyName];
// decipher the value
const ciphertext = encrypted.split('|')[1];
const plaintext = decrypt(ciphertext, encryptionKey);
const clarifiedKeys = querystring.parse(plaintext);
// add the clarified keys
Object.assign(allKeys, clarifiedKeys);
// remove the encrypted key
delete allKeys[ENCRYPTEDKEY];
}
return querystring.unescape(querystring.stringify(allKeys));
}
module.exports.obfuscate = obfuscate;
module.exports.clarify = clarify;