前端 aes 加密
2019-05-29 16:25 muamaker 阅读(1831) 评论(0) 编辑 收藏 举报
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>加密解密</title> <link rel="stylesheet" type="text/css" href="css/index.css"/> </head> <body> <h1>加密/解密</h1> <div class="wrap"> <div class="edit"> <textarea name="" rows="" cols="" id="edit"></textarea> </div> <p> <span>秘钥:</span><input type="text" name="" id="askey" value="" /> </p> <p> <span>矢量:</span><input type="text" name="" id="asvi" value="" /> </p> <div class="btns"> <span class="btn en">加密</span> <span class="btn den">解密</span> </div> <div class=""> <p>结果:</p> <div class="result"> </div> </div> </div> </body> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/crypto-js.js"></script> <script type="text/javascript"> function getAesString(data,key,iv){//加密 let keyed = CryptoJS.enc.Utf8.parse(key); // 加密秘钥 let ived = CryptoJS.enc.Utf8.parse(iv); // 矢量 let encryptResult = CryptoJS.AES.encrypt(data,keyed, { // AES加密 iv: ived, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 // 后台用的是pad.Pkcs5,前台对应为Pkcs7 }); return CryptoJS.enc.Base64.stringify(encryptResult.ciphertext); // Base64加密; } function getDAesString(data,key,iv){//解密 var keyed = CryptoJS.enc.Utf8.parse(key); var ived = CryptoJS.enc.Utf8.parse(iv); let baseResult=CryptoJS.enc.Base64.parse(data); // Base64解密 let ciphertext=CryptoJS.enc.Base64.stringify(baseResult); // Base64解密 let decryptResult = CryptoJS.AES.decrypt(ciphertext,keyed, { // AES解密 iv: ived, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return CryptoJS.enc.Utf8.stringify(decryptResult) } /*var res = getAesString("abc","1234567890000000","123456"); console.log(res); console.log(getDAesString(res,"1234567890000000","123456"));*/ var $result = $(".result"); var $edit = $("#edit"); var $askey = $("#askey"); var $asvi = $("#asvi"); $(".en").on("click",function(){ var askey = $askey.val(); if(askey.length % 4 !== 0 ){ alert("密钥长度必须是4的整数倍"); return ; } var res = getAesString($edit.val(),askey,$asvi.val()); $result.html(res); }); $(".den").on("click",function(){ var askey = $askey.val(); if(askey.length % 4 !== 0 ){ alert("密钥长度必须是4的整数倍"); return ; } var res = getDAesString($edit.val(),askey,$asvi.val()); $result.html(res); }) </script> </html>