-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (64 loc) · 2.2 KB
/
index.js
File metadata and controls
75 lines (64 loc) · 2.2 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
const CryptoJS = require('crypto-js')
/**
* Takes a object, transforms it to JSON and encrypts it using AES. The key is hashed to a SHA256 before use.
*
* @param {object} content The object that should be encrypted. The object is JSON.stringified before encryption
* @param {string} key Encryption key
* @returns {string} Encrypted object as a string
*/
const encrypt = (content, key) => {
if (!key) throw new Error('No key was provided to encrypt')
const json = JSON.stringify(content)
const hashedKey = CryptoJS.SHA256(key)
const encrypted = CryptoJS.AES.encrypt(json, hashedKey.toString())
return encrypted.toString()
}
/**
* Decrypts the content of the string using provided key and returns the object (JSON.parse()).
*
* @param {string} content The encrypted object
* @param {string} key Key used to decrypt object
* @returns {object} The decrypted object
*/
const decrypt = (content, key) => {
if (!key) throw new Error('No key was provided to decrypt')
const hashedKey = CryptoJS.SHA256(key)
const decrypted = CryptoJS.AES.decrypt(content, hashedKey.toString())
return JSON.parse(decrypted.toString(CryptoJS.enc.Utf8))
}
/**
* Takes a object and encrypts its values using the given secret.
*
* @param {object} content The object where the values should be encrypted
* @param {string} secret Encryption key.
* @returns {object} Object with encrypted values
*/
const encryptContent = (content, secret) => {
if (!secret) throw new Error('No secret was provided to encrypt')
const encrypted = {}
for (const key in content) {
encrypted[key] = encrypt(content[key], secret)
}
return encrypted
}
/**
* Takes the encrypted object and decrypts its values
*
* @param {object} content The object containing encrypted values (from encryptContent())
* @param {string} secret Encryption key to decrypt the values.
* @returns {object} Object with decrypted values
*/
const decryptContent = (content, secret) => {
if (!secret) throw new Error('No secret was provided to decrypt')
const decrypted = {}
for (const key in content) {
decrypted[key] = decrypt(content[key], secret)
}
return decrypted
}
module.exports = {
encryptContent,
decryptContent,
encrypt,
decrypt
}