2
0

👷 Transpile components for better DX

This commit is contained in:
Baptiste Arnaud
2022-09-18 09:46:42 +02:00
committed by Baptiste Arnaud
parent 898367a33b
commit c1dd4d403e
147 changed files with 343 additions and 485 deletions

View File

@ -0,0 +1,36 @@
import { randomBytes, createCipheriv, createDecipheriv } from 'crypto'
const algorithm = 'aes-256-gcm'
const secretKey = process.env.ENCRYPTION_SECRET
export const encrypt = (
data: object
): { encryptedData: string; iv: string } => {
if (!secretKey) throw new Error(`ENCRYPTION_SECRET is not in environment`)
const iv = randomBytes(16)
const cipher = createCipheriv(algorithm, secretKey, iv)
const dataString = JSON.stringify(data)
const encryptedData =
cipher.update(dataString, 'utf8', 'hex') + cipher.final('hex')
const tag = cipher.getAuthTag()
return {
encryptedData,
iv: iv.toString('hex') + '.' + tag.toString('hex'),
}
}
export const decrypt = (encryptedData: string, auth: string): object => {
if (!secretKey) throw new Error(`ENCRYPTION_SECRET is not in environment`)
const [iv, tag] = auth.split('.')
const decipher = createDecipheriv(
algorithm,
secretKey,
Buffer.from(iv, 'hex')
)
decipher.setAuthTag(Buffer.from(tag, 'hex'))
return JSON.parse(
(
decipher.update(Buffer.from(encryptedData, 'hex')) + decipher.final('hex')
).toString()
)
}