aboutsummaryrefslogtreecommitdiffstats
path: root/helpers/crypt.js
blob: 5d3d79ea171d0bb78b5c2f75302e44c6693e4d06 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const crypto = require('crypto')
const algorithm = 'aes-256-ctr'
const secretKey = process.env.MYAPPS_NOTES_KEY

export const encrypt = (text) => {
  const iv = crypto.randomBytes(16)
  const cipher = crypto.createCipheriv(algorithm, secretKey, iv)
  const encrypted = Buffer.concat([cipher.update(text), cipher.final()])

  return iv.toString('hex') + '::' + encrypted.toString('hex')
}

export const decrypt = (hash) => {
  const [iv, content] = hash.split('::')
  const decipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.from(iv, 'hex'))
  const decrpyted = Buffer.concat([decipher.update(Buffer.from(content, 'hex')), decipher.final()])

  return decrpyted.toString();
}