2020-07-29 js使用AES加解密

2020-08-04  本文已影响0人  Armin0202

背景

越来越严格的安全要求,迫使前端需要对交互报文进行加密。

方案

选择了AES加密方案

实现

AES-CBC

const aesjs = require('aes-js')

function CryptoCbc ({ key, iv }) {
  this.key = aesjs.utils.utf8.toBytes(key)
  this.iv = aesjs.utils.utf8.toBytes(iv)
}

// 加密
CryptoCbc.prototype.encrypt = function (text) {
  let aesCbc = new aesjs.ModeOfOperation.cbc(this.key, this.iv)
  let textBytes = aesjs.padding.pkcs7.pad(aesjs.utils.utf8.toBytes(text)) // 使用PKCS7Padding填充

  let encryptedBytes = aesCbc.encrypt(textBytes)
  let encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes) // 得到加密字符串
  return encryptedHex
}

// 解密
CryptoCbc.prototype.decrypt = function (encryptedHex) {
  let aesCbc = new aesjs.ModeOfOperation.cbc(this.key, this.iv)
  let encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex)

  var decryptedBytes = aesjs.padding.pkcs7.strip(aesCbc.decrypt(encryptedBytes))
  let decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes)
  return decryptedText
}

let cryptoCbc = new CryptoCbc({
  key: '39067A6F8088F81E9C2BB5D46A8C0F60', // 32位
  iv: 'EFEF3C38B05F5871' // 16位
})

let text = 'wEis11elYDR1aPWX123' // 待加密文本
let encryptedHex = cryptoCbc.encrypt(text) // 加密结果
let decryptedText = cryptoCbc.decrypt(encryptedHex) // 解密结果
console.log(encryptedHex)
console.log(decryptedText)

AES-ECB

const aesjs = require('aes-js')

function CryptoEcb ({ key }) {
  this.key = aesjs.utils.utf8.toBytes(key)
}

// 加密
CryptoEcb.prototype.encrypt = function (text) {
  let aesEcb = new aesjs.ModeOfOperation.ecb(this.key)
  let textBytes = aesjs.padding.pkcs7.pad(aesjs.utils.utf8.toBytes(text))

  let encryptedBytes = aesEcb.encrypt(textBytes)
  let encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes) // 得到加密字符串
  return encryptedHex
}

// 解密
CryptoEcb.prototype.decrypt = function (encryptedHex) {
  let aesEcb = new aesjs.ModeOfOperation.ecb(this.key)
  let encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex)

  var decryptedBytes = aesjs.padding.pkcs7.strip(aesEcb.decrypt(encryptedBytes))
  let decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes)
  return decryptedText
}

let cryptoEcb = new CryptoEcb({
  key: '39067A6F8088F81E9C2BB5D46A8C0F60', // 32位
})

let text = 'wEis11elYDR1aPWX123' // 待加密文本
let encryptedHex = cryptoEcb.encrypt(text) // 加密结果
let decryptedText = cryptoEcb.decrypt(encryptedHex) // 解密结果
console.log(encryptedHex)
console.log(decryptedText)

参考资料

上一篇下一篇

猜你喜欢

热点阅读