All files index.js

100% Statements 17/17
100% Branches 6/6
100% Functions 4/4
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x   4x 9x     3x 2x   1x 1x 1x 1x       3x 1x   2x         2x 2x 1x    
import crypto from 'crypto'
 
const algorithm = 'aes-256-cbc'
 
export const ivFromSecret = secret => secret.slice(0, 16)
export const isSecretValid = secret => !!secret && secret.length === 32
 
export function encrypt (text, secret) {
  if (!isSecretValid(secret)) {
    throw new Error('Secret must have 32 bytes.')
  }
  let cipher = crypto.createCipheriv(algorithm, secret, ivFromSecret(secret))
  let crypted = cipher.update(text, 'utf8', 'hex')
  crypted += cipher.final('hex')
  return crypted
}
 
export function decrypt (text, secret) {
  if (!isSecretValid(secret)) {
    throw new Error('Secret must have 32 bytes.')
  }
  let decipher = crypto.createDecipheriv(
    algorithm,
    secret,
    ivFromSecret(secret)
  )
  let dec = decipher.update(text, 'hex', 'utf8')
  dec += decipher.final('utf8')
  return dec
}