-
Notifications
You must be signed in to change notification settings - Fork 4
/
encryption.js
45 lines (38 loc) · 1.15 KB
/
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
45
import sodium from 'libsodium-wrappers'
const key = process.env.ENCRYPTION_SECRET_KEY
const encrypt = async plaintext => {
await sodium.ready
const nonce = Buffer.from(sodium.randombytes_buf(24))
const ciphertext = Buffer.from(
sodium.crypto_secretbox_easy(plaintext, nonce, Buffer.from(key, 'hex')),
)
return {ciphertext: ciphertext.toString('hex'), nonce: nonce.toString('hex')}
}
const decrypt = async (accessToken = {}) => {
const {ciphertext, nonce} = accessToken
try {
await sodium.ready
const decrypted = Buffer.from(
sodium.crypto_secretbox_open_easy(
Buffer.from(ciphertext, 'hex'),
Buffer.from(nonce, 'hex'),
Buffer.from(key, 'hex'),
),
)
return sodium.to_string(decrypted)
} catch (e) {
console.error(e)
return null
}
}
const encryptionKeygen = async () => {
await sodium.ready
const key = Buffer.from(sodium.crypto_secretbox_keygen())
return key.toString('hex')
}
const hmacKeygen = async () => {
await sodium.ready
const hmacKey = Buffer.from(sodium.crypto_auth_keygen())
return hmacKey.toString('hex')
}
export {encrypt, decrypt, encryptionKeygen, hmacKeygen}