sensitive-aes-cipher.js 1.3 KB
Newer Older
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
const crypto = require('crypto')
const { ERROR } = require('./error')

function checkSecret (secret) {
  if (!secret) {
    throw {
      errCode: ERROR.CONFIG_FIELD_REQUIRED,
      errMsgValue: {
        field: 'sensitiveInfoEncryptSecret'
      }
    }
  }

  if (secret.length !== 32) {
    throw {
      errCode: ERROR.CONFIG_FIELD_INVALID,
      errMsgValue: {
        field: 'sensitiveInfoEncryptSecret'
      }
    }
  }
}
function encryptData (text = '') {
  if (!text) return text

  const encryptSecret = this.config.sensitiveInfoEncryptSecret

  checkSecret(encryptSecret)

  const iv = encryptSecret.slice(-16)

  const cipher = crypto.createCipheriv('aes-256-cbc', encryptSecret, iv)

  const encrypted = Buffer.concat([
    cipher.update(Buffer.from(text, 'utf-8')),
    cipher.final()
  ])

  return encrypted.toString('base64')
}

function decryptData (text = '') {
  if (!text) return text

  const encryptSecret = this.config.sensitiveInfoEncryptSecret

  checkSecret(encryptSecret)

  const iv = encryptSecret.slice(-16)

  const cipher = crypto.createDecipheriv('aes-256-cbc', encryptSecret, iv)

  const decrypted = Buffer.concat([
    cipher.update(Buffer.from(text, 'base64')),
    cipher.final()
  ])

  return decrypted.toString('utf-8')
}

module.exports = {
  encryptData,
  decryptData
}