【问题标题】:Unable to decrypt aes-192-gcm无法解密 aes-192-gcm
【发布时间】:2019-08-02 01:39:00
【问题描述】:

我在用nodejs加解密aes-192-gcm

这是我的代码:

const encrypted = decrypt.encryptText('aes-192-gcm', 'FnpkKuIoqZL5B3tnE0Htmg==', '1z3FtB6OitmFOIsP', 'helloWorld', 'base64');
const de = decrypt.decryptText('aes-192-gcm', 'FnpkKuIoqZL5B3tnE0Htmg==', '1z3FtB6OitmFOIsP', encrypted, 'utf-8');
console.log(encrypted);
console.log(de);

使用的功能:

 function encryptText(cipher_alg, key, iv, text, encoding) {

        var cipher = crypto.createCipheriv(cipher_alg, key, iv);

        encoding = encoding || "binary";

        var result = cipher.update(text, "utf8", encoding);
        result += cipher.final(encoding);

        return result;
    }

    function decryptText(cipher_alg, key, iv, text, encoding) {

        const decipher = crypto.createDecipheriv(cipher_alg, key, iv);

        encoding = encoding || "binary";

        let result = decipher.update(text, encoding);
        result += decipher.final();

        return result;
    }

我得到的错误:

Unsupported state or unable to authenticate data

【问题讨论】:

    标签: aes-gcm encryption


    【解决方案1】:

    NodeJS 的加密模块使用 OpenSSL。此 API 具有 GCM / AEAD 密码的特殊参数。 API 中添加了使用它们的方法,例如getAuthTagsetAuthTag。如果没有后者,方法always 会抛出 GCM 模式解密的异常。该标签(幸运的是)被认为是 NodeJS / OpenSSL 中密文的一部分。其他语言运行时(例如 Java)确实将其视为密文的一部分。

    【讨论】:

      【解决方案2】:

      几个问题

      1. 您为 decryptText() 传递了错误的编码格式
      2. 使用 GCM、CCM 和 OCB 时需要 AuthTag。

      我附上了一个基于你分享的 sn-p 的示例代码。

      var cipherTag;
      
      const encrypted = encryptText('aes-192-gcm', 'FnpkKuIoqZL5B3tnE0Htmg==', '1z3FtB6OitmFOIsP', 'helloWorld', 'base64');
      const de = decryptText('aes-192-gcm', 'FnpkKuIoqZL5B3tnE0Htmg==', '1z3FtB6OitmFOIsP', encrypted, 'base64');
      console.log(encrypted);
      console.log(de);
      
      function encryptText(cipher_alg, key, iv, text, encoding) {
      
          var cipher = crypto.createCipheriv(cipher_alg, key, iv);
      
          encoding = encoding || "binary";
      
          var result = cipher.update(text, "utf8", encoding);
          result += cipher.final(encoding);
          cipherTag = cipher.getAuthTag();
          return result;
      }
      
      function decryptText(cipher_alg, key, iv, text, encoding) {
      
          const decipher = crypto.createDecipheriv(cipher_alg, key, iv);
      
          encoding = encoding || "binary";
          decipher.setAuthTag(cipherTag);
          let result = decipher.update(text, encoding, 'utf8');
          result+= decipher.final('utf8');
          return result.toString();
      }
      

      // 会输出

      b2SMQRBt/EgNgQ==
      helloWorld
      

      【讨论】:

      • 我认为这里不需要 setAAD,问题是她缺少 authTag
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 2013-08-11
      • 1970-01-01
      • 2020-07-03
      • 2020-09-08
      • 2019-01-31
      • 2020-10-16
      相关资源
      最近更新 更多