美文网首页
aes cbc加密

aes cbc加密

作者: jiaomeichen | 来源:发表于2018-10-08 13:38 被阅读0次

aes 128 cbc加密

          function encrypt(msg, key, iv) {//加密
                var key =    CryptoJS.enc.Utf8.parse(key);//Base64字符串-->WordPress对象
                var iv =    CryptoJS.enc.Utf8.parse(iv);
                return CryptoJS.AES.encrypt(msg, key, {
                    iv: iv,
                    padding: CryptoJS.pad.Pkcs7,
                    mode: CryptoJS.mode.CBC
                });
            }

            var data = "2018E22030800024";
            var key="kunlun8888888888";
            var iv = "1234567812345678"
            var encrypted = encrypt(data, key, iv);
            var cipherText = encrypted.toString();
            /**/
           console.log("原串:"+data)
           console.log("加密:"+cipherText);
  • aes 256 cbc加密
var message = "20181100160000018417";//utf8字符串,待加密
            var iv = "1234567812345678";        
            var key = "kunlun8888888888";//秘钥。长度32的16进制字符串。
            var cryptkey  = CryptoJS.enc.Utf8.parse(key);//将16进制字符串转换为 WordArray对象
            //或者 
            //var key = "qwertyuiopasdfgh";//长度16的utf8字符串
            //var cryptkey =  CryptoJS.enc.Utf8.parse(key);//将utf8字符串转换为 WordArray对象
            //重点是 key要转换为WordArray对象,加密时要用。
            
            //测试
            var ciphertext = aesEncrypt(message,cryptkey,iv);//加密
            var decryptedMessage = aesDecrypt(ciphertext,cryptkey,iv);//解密
            console.log("原串:"+message)
            console.log("加密:"+ciphertext)
            console.log("解密:"+decryptedMessage);
            
            
            function aesEncrypt(message,key,iv){
                var ciphertext = CryptoJS.AES.encrypt(message, key, {   
                    iv: CryptoJS.enc.Utf8.parse(iv),
                    mode: CryptoJS.mode.CBC,
                    padding:CryptoJS.pad.Pkcs7 
                });
                return CryptoJS.enc.Base64.stringify(ciphertext.ciphertext);//密文 转 Base64字符串
            }
            
            //解密函数 稍有改动。
            function aesDecrypt(crypted,key,iv){
                var decrypted = CryptoJS.AES.decrypt({ciphertext: CryptoJS.enc.Base64.parse(crypted)},key,{
                    iv: CryptoJS.enc.Utf8.parse(iv),
                    mode: CryptoJS.mode.CBC,
                    padding:CryptoJS.pad.Pkcs7 
                });
                return decrypted.toString(CryptoJS.enc.Utf8);
            }

相关文章

网友评论

      本文标题:aes cbc加密

      本文链接:https://www.haomeiwen.com/subject/oswljftx.html