前端加密传输 crypto-js AES 加密和解密
Posted 肖秋雄
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端加密传输 crypto-js AES 加密和解密相关的知识,希望对你有一定的参考价值。
配置:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Document</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script> <script> 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 = \'12345678910\'; //密钥 var iv = \'12345678910\'; var encrypted = getAesString(data, key, iv); //密文 var encrypted1 = CryptoJS.enc.Utf8.parse(encrypted); return encrypted; } function getDAes(data) { //解密 var key = \'12345678910\'; //密钥 var iv = \'12345678910\'; //密钥偏移量 var decryptedStr = getDAesString(data, key, iv); return decryptedStr; } var AES = getAES(\'hello\'); var AFTERAES = getDAes(AES); console.log(\'加密后:\' + AES ); console.log(\'解密后:\' + AFTERAES ); </script> </body> </html>
以上是关于前端加密传输 crypto-js AES 加密和解密的主要内容,如果未能解决你的问题,请参考以下文章