JS AES加密,解密(crypto-js)

首次发布:2024-08-13 08:15
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS AES加密</title>
    <script src="http://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.js"></script>
</head>
<body class="user-select single">
    本文来自www.luofenming.com
    <script type="text/javascript">

        function encrypt(data, key) {
            //var iv = CryptoJS.enc.Utf8.parse(''); // 向量
            // 加密数据
            let encrypted = CryptoJS.AES.encrypt(data, key, {
                //iv: iv,
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            // 转换为字符串(Base64编码)
            let encryptedString = encrypted.toString();
            return encryptedString
        }
        
        function decrypt(data, key) {
            var bytes = CryptoJS.AES.decrypt(data, key, {
                //iv: CryptoJS.enc.Utf8.parse(""),
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            var decryptResult = bytes.toString(CryptoJS.enc.Utf8);
            return decryptResult;
        }
        
//-------方法调用-------------------------------------------------------------------------
        var data = "这是需要加密的数据www.luofenming.com";

        // 密钥
        let key = CryptoJS.enc.Utf8.parse('e10adc3949ba59abbe56e057f2012345'); // 长度32密钥

        let str = encrypt(data, key);
        console.log("加密后的结果", str);
        let dStr = decrypt(str, key);
        console.log("解密后的结果", dStr);
    </script>
</body>
</html>

本文来自 www.luofenming.com