美文网首页
crypto-js实现加密解密

crypto-js实现加密解密

作者: 笑才 | 来源:发表于2019-06-13 00:54 被阅读0次

    1、DES加密

               function encryptByDESModeEBC(str,key){//str为待加密字符串,key为密匙
                var keyHex = CryptoJS.enc.Utf8.parse(key);
                var encrypted = CryptoJS.DES.encrypt(str, keyHex, {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
                });
                return encrypted.ciphertext.toString();
            }
    

    2、DES解密

                  function decryptByDESModeEBC(ciphertext,key){//ciphertext为带解密字符串,key为密匙
                var keyHex = CryptoJS.enc.Utf8.parse(key);
                var decrypted = CryptoJS.DES.decrypt({
                ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
                }, keyHex, {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
                });
                var result_value = decrypted.toString(CryptoJS.enc.Utf8);
                return result_value;
            }
    

    3、AES加密

                    function getAES(data){ //加密
                var key  = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';  //密钥
                var iv   = '1234567812345678';  //十六位十六进制数作为密钥偏移量
                var encrypted =getAesString(data,key,iv); //密文
                var encrypted1 =CryptoJS.enc.Utf8.parse(encrypted);
                return encrypted;
            }
    
                    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格式的密文
            }
    

    4、AES解密

                  function getDAes(data){//解密
                var key  = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';  //密钥
                var iv   = '1234567812345678';  //十六位十六进制数作为密钥偏移量
                var decryptedStr =getDAesString(data,key,iv);
                return decryptedStr;
            }
    
                    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);     
            }
    

    5、注意:js的前端加密不能与java加密代码写的代码混合使用

    相关文章

      网友评论

          本文标题:crypto-js实现加密解密

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