sensitive-aes-cipher.js 1.2 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
const crypto = require('crypto')

function checkSecret (secret) {
  if (!secret) {
    throw {
      errCode: '请在config.json中配置sensitiveInfoEncryptSecret字段'
    }
  }

  if (secret.length < 32) {
    throw {
      errCode: 'sensitiveInfoEncryptSecret字段长度不能小于32位'
    }
  }
}
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
}