AES加密的两种方式ECB与CBC
AES为对称加密
ECB只需要秘钥key、而CBC需要秘钥key和iv,相当于需要两把钥匙。
本文使用的是JavaScript代码实现,需要引入js文件
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
CBC实现代码如下
function getAesString(data,key,iv){//加密
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var encrypted =CryptoJS.AES.encrypt(data,key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return encrypted.toString(); //返回的是base64格式的密文
}
function getDAesString(encrypted,key,iv){//解密
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var decrypted =CryptoJS.AES.decrypt(encrypted,key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
function getAES(data){ //加密
var key = '8765432187654321'; //密钥
var iv = '1234567812345678';
var encrypted =getAesString(data,key,iv); //密文
var encrypted1 =CryptoJS.enc.Utf8.parse(encrypted);
return encrypted;
}
function getDAes(data){//解密
var key = '8765432187654321'; //密钥
var iv = '1234567812345678';
var decryptedStr =getDAesString(data,key,iv);
return decryptedStr;
}
var aa = getAES("github.com");
var bb = getDAes(aa);
console.log(aa,bb);
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
参考资料: https://blog.csdn.net/sinat_28371057/article/details/114608647