-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (38 loc) · 1.17 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
import crypto from 'crypto'
export { default as awsKms } from './lib/awsKms.js'
export { default as dummyKms } from './lib/dummyKms.js'
export { default as kekService } from './lib/kekService.js'
const defaults = {
encoding: 'hex'
}
export const createEnvelopeEncryptor = (keyService, options = defaults) => {
const { encoding } = options
const algorithm = 'aes256'
const { getDataKey, decryptDataKey } = keyService
const encrypt = async (plaintext) => {
const { encryptedKey, plaintextKey } = await getDataKey()
const salt = Buffer.from(crypto.randomBytes(8)).toString('hex')
const cipher = crypto.createCipheriv(algorithm, plaintextKey, salt)
const ciphertext = [
cipher.update(plaintext, 'utf8', encoding),
cipher.final(encoding)
].join('')
return {
ciphertext,
key: encryptedKey,
salt
}
}
const decrypt = async ({ ciphertext, key, salt }) => {
const dataKey = await decryptDataKey(key)
const decipher = crypto.createDecipheriv(algorithm, dataKey, salt)
return [
decipher.update(ciphertext, encoding, 'utf8'),
decipher.final('utf8')
].join('')
}
return {
decrypt,
encrypt
}
}