JS加解密之AES


 

 

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, "");

 

JAVA加解密之AES:https://www.cnblogs.com/pxblog/p/17070855.html

 

posted @ 2023-01-28 15:54  yvioo  阅读(1268)  评论(0编辑  收藏  举报