无法解密aes-192-gcm

时间:2019-07-31 21:03:45

标签: aes-gcm encryption

我正在使用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

2 个答案:

答案 0 :(得分:2)

问题夫妇

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

我已根据您共享的代码片段附加了示例代码。

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

答案 1 :(得分:2)

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