温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Crypto: encrypt or decrypt string
javascript node.js string cryptojs

javascript - 加密:加密或解密字符串

发布于 2020-03-28 23:32:10

我尝试对cookieStorage中的字符串进行加密和解密,但是当我执行代码时,我收到类似此方法的消息,并且此方法不起作用

我的代码:

    const crypto = requite('crypto');        

    app.get("/crypto", (req, res) => {
       var word = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlMzBiZjE0YmQ4OTNmMmE5Y2Q1Y2I5MSIsInJvbGVzIjoiVVNFUl9ST0xFIiwiZW1haWwiOiJjYW1lcmF0ZXN0ODExQGdtYWlsLmNvbSIsImlhdCI6MTU4MDMzNjc1MCwiZXhwIjoxNTgwMzk2NzUwfQ.2bbqkoX7qhyX7lyLjBtlGPe08-oHGjO83nNIPxAzHv8";
      var algorithm = "aes-256-ct";
      var password = "3zTvzr3p67VC61jmV54rIYu1545x4TlY";
      var hw = encrypt(word, algorithm, password);
      console.log("encrypt: ", hw);
      console.log("decrypt: ", decrypt(hw, algorithm, password));
    });

    function encrypt(text, algorithm, password) {
      var cipher = crypto.createCipher(algorithm, password);
      var crypted = cipher.update(text, "utf8", "hex");
      crypted += cipher.final("hex");
      return crypted;
    }

    function decrypt(text, algorithm, password) {
      var decipher = crypto.createDecipher(algorithm, password);
      var dec = decipher.update(text, "hex", "utf8");
      dec += decipher.final("utf8");
      return dec;
    }

查看更多

查看更多

提问者
Valentyn SHCHERBOV
被浏览
153
Valentyn SHCHERBOV 2020-01-31 17:44

它的工作与此:

exports.encrypt = (text, ENCRYPTION_KEY, IV_LENGTH) => {
    let iv = crypto.randomBytes(IV_LENGTH);
    let cipher = crypto.createCipheriv(
      "aes-256-cbc",
      Buffer.from(ENCRYPTION_KEY),
      iv
    );
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString("hex") + ":" + encrypted.toString("hex");
  }

  exports.decrypt = (text, ENCRYPTION_KEY, IV_LENGTH) => {
    let textParts = text.split(":");
    let iv = Buffer.from(textParts.shift(), "hex");
    let encryptedText = Buffer.from(textParts.join(":"), "hex");
    let decipher = crypto.createDecipheriv(
      "aes-256-cbc",
      Buffer.from(ENCRYPTION_KEY),
      iv
    );
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
  }