【问题标题】:Crypto: encrypt or decrypt stringCrypto:加密或解密字符串
【发布时间】:2020-01-31 18:02:09
【问题描述】:

我尝试在 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;
    }

【问题讨论】:

  • 嗨。一种方法已经过时了,但是……哪一种?
  • 尝试查看 API:nodejs.org/api/crypto.html
  • 此方法:createCipher 和 createDecipher
  • 有待阅读的错误消息或警告,通常会提供有关如何解决问题的非常具体的信息。
  • 我放了两个console.log,但它没有显示,我有一个警告(createCipher 和 createDecipher)不推荐使用它

标签: javascript node.js string cryptojs


【解决方案1】:

它适用于这个:

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();
  }

【讨论】:

    【解决方案2】:

    createCipher 已弃用,请改用crypto.createCipheriv()

    createDecipher 已弃用,请改用crypto.createDecipheriv()

    来源:https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options

    【讨论】:

    • 我用过 (crypto.createCipheriv() 和 crypto.createDecipheriv()) 但是console.log什么都不显示
    【解决方案3】:

    你可以使用 npm crypto-js 来加密和解密里面的字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2012-07-01
      • 2018-08-26
      相关资源
      最近更新 更多