编程语言
首页 > 编程语言> > Javascript实现AES加密解密(ECB/CBC)

Javascript实现AES加密解密(ECB/CBC)

作者:互联网

环境配置

ECB加密解密

var key = CryptoJS.enc.Utf8.parse("zhgerXHBVaaKm8xy")
var plaintText = 'onlystar'
var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
    mode: CryptoJS.mode.ECB,  
    padding: CryptoJS.pad.Pkcs7
})

console.log("加密前:"+plaintText) // 加密前:onlystar
console.log("加密后:"+encryptedData) // 加密后:cp7hxlPgStaA4Jod5uKCuQ==

encryptedData = encryptedData.ciphertext.toString()

var encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedData)
console.log("解密前hex:"+encryptedHexStr) // 解密前hex:729ee1c653e04ad680e09a1de6e282b9
var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr)
console.log("解密前:"+encryptedBase64Str) // 解密前:cp7hxlPgStaA4Jod5uKCuQ==
var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, { 
    mode: CryptoJS.mode.ECB,  
    padding: CryptoJS.pad.Pkcs7
})

var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8)
console.log("解密后:"+decryptedStr) // 解密后:onlystar

CBC加密解密

var key = CryptoJS.enc.Utf8.parse("zhgerXHBVaaKm8xy")
var plaintText = 'onlystar'
var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
    iv:  CryptoJS.enc.Utf8.parse(key),
    mode: CryptoJS.mode.CBC,  
    padding: CryptoJS.pad.Pkcs7
})

console.log("加密前:"+plaintText) // 加密前:onlystar
console.log("加密后:"+encryptedData) // 加密后:cp7hxlPgStaA4Jod5uKCuQ==

encryptedData = encryptedData.ciphertext.toString()

var encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedData)
console.log("解密前hex:"+encryptedHexStr) // 解密前hex:729ee1c653e04ad680e09a1de6e282b9
var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr)
console.log("解密前:"+encryptedBase64Str) // 解密前:cp7hxlPgStaA4Jod5uKCuQ==
var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, { 
    iv:  CryptoJS.enc.Utf8.parse(key),
    mode: CryptoJS.mode.CBC,  
    padding: CryptoJS.pad.Pkcs7
})

var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8)
console.log("解密后:"+decryptedStr) // 解密后:onlystar

封装方法

const DecryptEcb = (keyword, secretKey) => {
  try {
    let key = CryptoJS.enc.Utf8.parse(secretKey)
    let encryptedHexStr = CryptoJS.enc.Hex.parse(keyword)
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
    let decrypt = CryptoJS.AES.decrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding })
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
  } catch (error) {
    console.log(error)
    return ''
  }
}

使用

const { username, password, secretKey } = data
// 解密
const user = DecryptEcb(username, secretKey)
const pwd = DecryptEcb(password, secretKey)

标签:CBC,AES,enc,console,ECB,解密,mode,var,CryptoJS
来源: https://blog.csdn.net/sinat_28371057/article/details/114608647