小程序:JS AES加密解密(ECB/CBC)

序言:介绍一下javascript下AES加密和解密,运用的工作模式为ECB(电码本模式Electronic Codebook Book),填充方式为(NoPadding),及CBC(密码分组链接模式Cipher Block Chaining)。这里用到的是CryptoJS。

    1. 将components下的aes.js,mode-ecb.js和pad-nopadding.js添加到项目中utils目录下。

      形如:
      1.png
    1. 新建aesTool.js封装一下加密解密的方法。
var CryptoJS = require('./aes.js');
const fillPadding = require('./pad-nopadding.js');
const workMode = require('./mode-ecb.js');
var key = CryptoJS.enc.Hex.parse("122a3b4c5d6f7g8h122a3b4c5d6f7g8h");
/**
   * AES加密(ECB,NoPadding)
   */
function Encrypt_ecb(word) {
  var srcs = CryptoJS.enc.Hex.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding
  });
  return encrypted.ciphertext.toString().toUpperCase();
}
/**
   * AES加密(ECB,NoPadding)
   */
function Encrypt_cbc(word) {
  var srcs = CryptoJS.enc.Hex.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: CryptoJS.enc.Utf8.parse("0000000000000000"), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
  return encrypted.ciphertext.toString().toUpperCase();
}
/**
   * AES解密(ECB,NoPadding)
   */
function Decrypt_ecb(word) {
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decrypt = CryptoJS.AES.decrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
  var decryptedStr = decrypt.toString(CryptoJS.enc.Hex);
  return decryptedStr.toString();
}

/**
   * AES解密(CBC,Pkcs7)
   */
function Decrypt_cbc(word) {
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decrypt = CryptoJS.AES.decrypt(word, key, { iv: CryptoJS.enc.Utf8.parse("0000000000000000"), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  var decryptedStr = decrypt.toString(CryptoJS.enc.Hex);
  return decryptedStr.toString();
}

module.exports = {
  Encrypt_ecb: Encrypt_ecb,
  Decrypt_ecb: Decrypt_ecb,
  Encrypt_cbc: Encrypt_cbc,
  Decrypt_cbc: Decrypt_cbc,
}
    1. 使用方法:
///演示ECB模式
var aesTool = require('../../utils/aesTool.js')
const aesSource = "---content---"
console.log("加密前:" + aesString)
var aesBuffer = aesTool.Encrypt_ecb(aesString)
console.log("加密后:" + aesBuffer)
var decryData = aesTool.Decrypt_ecb(aesBuffer)
console.log("解密后:" + decryData)

推荐阅读更多精彩内容