demo
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script> <script> alert(aesDecrypt(aesEncrypt("yvioo","wa1234535"),"wa1234535")) /** * 加密字符串 * @param str 要加密的字符串 * @param key 秘钥 * @returns {string} */ function aesEncrypt(str, key) { var APIFMS; try { var keyHex_encrypt = CryptoJS.enc.Utf8.parse(key); var encrypted = CryptoJS.AES.encrypt(str, keyHex_encrypt, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); APIFMS = CryptoJS.enc.Base64.stringify(encrypted.ciphertext); } catch (err) { console.log('aes 加密 -------------------------'); console.log(err); } return APIFMS; } /** * 解密字符串 * @param str 要解密的字符串 * @param key 秘钥 * @returns {string} */ function aesDecrypt(str, key) { var result_value; try { var keyHex_decrypt = CryptoJS.enc.Utf8.parse(key); var decrypted = CryptoJS.AES.decrypt({ ciphertext: CryptoJS.enc.Base64.parse(str) }, keyHex_decrypt, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); result_value = decrypted.toString(CryptoJS.enc.Utf8); } catch (err) { console.log('aes 解密 ------------------------- '); console.log(err); console.log("解密前数据:" + str); } return result_value; } </script>
如果解密出现异常:Error: Malformed UTF-8 data
看下是不是因为密文含有换行符\r\n 如果有要把这种去掉
str = str.toString().replace(/\r|\n/ig, "");
标签:AES,enc,console,key,加解密,JS,str,var,CryptoJS From: https://www.cnblogs.com/pxblog/p/17070480.html