sensitive-aes-cipher.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const crypto = require('crypto')
  2. const { ERROR } = require('./error')
  3. function checkSecret (secret) {
  4. if (!secret) {
  5. throw {
  6. errCode: ERROR.CONFIG_FIELD_REQUIRED,
  7. errMsgValue: {
  8. field: 'sensitiveInfoEncryptSecret'
  9. }
  10. }
  11. }
  12. if (secret.length !== 32) {
  13. throw {
  14. errCode: ERROR.CONFIG_FIELD_INVALID,
  15. errMsgValue: {
  16. field: 'sensitiveInfoEncryptSecret'
  17. }
  18. }
  19. }
  20. }
  21. function encryptData (text = '') {
  22. if (!text) return text
  23. const encryptSecret = this.config.sensitiveInfoEncryptSecret
  24. checkSecret(encryptSecret)
  25. const iv = encryptSecret.slice(-16)
  26. const cipher = crypto.createCipheriv('aes-256-cbc', encryptSecret, iv)
  27. const encrypted = Buffer.concat([
  28. cipher.update(Buffer.from(text, 'utf-8')),
  29. cipher.final()
  30. ])
  31. return encrypted.toString('base64')
  32. }
  33. function decryptData (text = '') {
  34. if (!text) return text
  35. const encryptSecret = this.config.sensitiveInfoEncryptSecret
  36. checkSecret(encryptSecret)
  37. const iv = encryptSecret.slice(-16)
  38. const cipher = crypto.createDecipheriv('aes-256-cbc', encryptSecret, iv)
  39. const decrypted = Buffer.concat([
  40. cipher.update(Buffer.from(text, 'base64')),
  41. cipher.final()
  42. ])
  43. return decrypted.toString('utf-8')
  44. }
  45. module.exports = {
  46. encryptData,
  47. decryptData
  48. }