节点加密createDecipheriv抛出无效的密钥长度错误

时间:2017-02-10 19:41:45

标签: node.js cryptography rsa

大家好:我使用NodeRSA通过以下行生成私钥 - 公钥对:

const key = new nodeRSA();
key.generateKeyPair(2048, 65537);

删除页眉和页脚\n后,该对看起来像这样:

//only for demo
"publicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlJ3PpWq77KY+tFccFfH4bO65Nu82LyzX0FxYGZ/QaF+LuZqeXEErXUO5iJ3P+hPRtiHUEHr9d5mfqStA/DnXxBbFmbwatNE8ncu4pSBOr9pbUyt22BRVkaiBBN0IuzBwo4ZWNrsON7IolVJnh8BKyurO5r7uj3aa8Yz0wcwIIkgais967iFWoj8YyeMSXpqUuMQu4mvcWB0EY/+wJNQnlSf7WuoJaTtzPzLe0qBaGnYO01ASxeOgPRzAJJ8prz2xZ5xy1nW+w+88XHVQsQizJ32B5Mzw7CpAeKIAnhlMVs8gVVc7iCfiwLoMiZXSReNxl2WfIYbHpaH2e6kPZoYNLQIDAQAB",


"privateKey": "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCUnc+larvspj60VxwV8fhs7rk27zYvLNfQXFgZn9BoX4u5mp5cQStdQ7mInc/6E9G2IdQQev13mZ+pK0D8OdfEFsWZvBq00Tydy7ilIE6v2ltTK3bYFFWRqIEE3Qi7MHCjhlY2uw43siiVUmeHwErK6s7mvu6PdprxjPTBzAgiSBqKz3ruIVaiPxjJ4xJempS4xC7ia9xYHQRj/7Ak1CeVJ/ta6glpO3M/Mt7SoFoadg7TUBLF46A9HMAknymvPbFnnHLWdb7D7zxcdVCxCLMnfYHkzPDsKkB4ogCeGUxWzyBVVzuIJ+LAugyJldJF43GXZZ8hhselofZ7qQ9mhg0tAgMBAAECggEBAI3lt9Mq+89SU+CAo7JYXGg17uYCtGuKl2y8Huooayacw54tgTJ4jtz3wvgsJd2SetM5rW8m30gIiCdPwzaQS/FQBM9qiN1IQmYvk1cmZ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mhdPOhisMVy1P8T7Hfsx7T/peEg=="

我使用上面的公钥加密某些数据,然后通过以下行解密上述私钥(转换为缓冲区):

// ivBuf is the buffer of initialization vector
crypto.createDecipheriv('aes-256-gcm', privateKeyBuf, ivBuf);

但Node crypto抱怨:

crypto.js:235
  this._handle.initiv(cipher, toBuf(key), toBuf(iv));
               ^

Error: Invalid key length
    at Error (native)
    at new Decipheriv (crypto.js:235:16)
    at Object.Decipheriv (crypto.js:232:12)

问题是:为什么关键长度无效?

谢谢!

1 个答案:

答案 0 :(得分:0)

crypto模块使用的默认字符串编码从二进制更改为utf8。因此,您的二进制字符串被解释为utf8,并且在转换过程中很可能变得大于16个字节