const crypto = require('crypto')
const ALGORITHM_NAME = 'aes-256-cbc'
const ENCRYPT_KEY = 'e916e810f3858bffc8751581ca81a748'
const IV_LENGTH = 16
const NONCE_LENGTH = 4

const encryptString = (plainText) => {
  const nonce = crypto.randomBytes(NONCE_LENGTH)
  const iv = crypto.randomBytes(IV_LENGTH)
  const cipher = crypto.createCipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv)
  let encrypted = cipher.update(plainText, 'utf8', 'hex')
  encrypted += cipher.final('hex')
  const cipherText = Buffer.concat([iv, nonce, Buffer.from(encrypted, 'hex')])
  return cipherText.toString('hex')
}

const decryptString = (cipherText) => {
  const cipherByte = Buffer.from(cipherText, 'hex')
  const iv = cipherByte.slice(0, IV_LENGTH)
  const originalText = cipherByte.slice(IV_LENGTH + NONCE_LENGTH, cipherByte.length)
  let decipher = crypto.createDecipheriv(ALGORITHM_NAME, ENCRYPT_KEY, iv)
  let decrypted = decipher.update(originalText.toString('hex'), 'hex', 'utf8')
  decrypted += decipher.final('utf8')
  return decrypted
}