美文网首页
crypto-js and native nodejs modu

crypto-js and native nodejs modu

作者: JoneSnow | 来源:发表于2020-04-29 12:01 被阅读0次

    native node crypto

    var Crypto = require("crypto");
    
    var Cipher = {
      pass: "0123456789abcdef0123456789abcdef",
      iv: "0123456789abcdef",
      encript: function (msg) {
        try {
          var cipher = Crypto.createCipheriv("aes-256-cbc", this.pass, this.iv);
          var hash = cipher.update(msg, 'utf8', "hex");
          return hash + cipher.final("hex");
        } catch (err) {
          console.error(err);
          return "";
        }
      },
      decript: function (hex){
        try {
          var decipher = Crypto.createDecipheriv("aes-256-cbc", this.pass, this.iv);
          var dec = decipher.update(hex, "hex", 'utf8');
          return dec + decipher.final('utf8');
        } catch (err) {
          console.error(err);
          return "";
        }
      }
    }
    var encripted = Cipher.encript("i have an apple");
    console.log(encripted);
    var decripted = Cipher.decript(encripted);
    console.log(decripted);
    
    

    crypto-js

    var CryptoJS = require("crypto-js");
    var Cipher = {
      pass: CryptoJS.enc.Utf8.parse("0123456789abcdef0123456789abcdef"),
      iv: CryptoJS.enc.Utf8.parse("0123456789abcdef"),
      encript: function (msg) {
        try {
          var options = { mode: CryptoJS.mode.CBC, iv: this.iv};
          var json = CryptoJS.AES.encrypt(msg, this.pass, options);
          return json.ciphertext.toString(CryptoJS.enc.Hex);
        } catch (err) {
          console.error(err);
          return "";
        }
      },
      decript: function (hex){
        try {
          var options = { mode: CryptoJS.mode.CBC, iv: this.iv};
          var json = CryptoJS.AES.decrypt({
            ciphertext: CryptoJS.enc.Hex.parse(hex)
          }, this.pass, options);
          return json.toString(CryptoJS.enc.Utf8);
        } catch (err) {
          console.error(err);
          return "";
        }
      }
    };
    
    var encripted = Cipher.encript("ruigu");
    console.log(encripted);
    var decripted = Cipher.decript(encripted);
    console.log(decripted);
    
    

    相关文章

      网友评论

          本文标题:crypto-js and native nodejs modu

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