【问题标题】:Node.js verify.verify() strange behaviourNode.js verify.verify() 奇怪的行为
【发布时间】:2018-09-28 17:39:47
【问题描述】:

我一直在开发一个数字签名 node.js 应用程序,然后我遇到了我无法弄清楚的奇怪行为。

首先我将公钥/私钥对生成为described here

然后我实现了以下脚本

  const crypto = require('crypto');
  const fs = require('fs');
  const privateKey = fs.readFileSync('./private_key.pem');
  const publicKey = fs.readFileSync('./public_key.pem');
  const hashAlg = 'sha256'
  const data = Buffer.from('test signature'.repeat(100), 'utf8');

  let bytes = []
  // sign
  const sign = crypto.createSign(hashAlg);
  sign.update(data);
  const signature = sign.sign(privateKey);
  fs.writeFileSync(`./signature.${hashAlg}`, publicKey);
  const verifier = crypto.createVerify(hashAlg);
  verifier.update(data);
  const result = verifier.verify(publicKey, signature);
  for(let i=0; i < publicKey.length ; i++){
    try{
      const verifier2 = crypto.createVerify('RSA-SHA256');
      verifier2.update(data);
      const invalidPublicKey = Buffer.from(publicKey);
      invalidPublicKey[i] = invalidPublicKey[i]+1;
      const result2 = verifier2.verify(invalidPublicKey, signature);
      if(result2) {
        bytes.push(i);
      };
    } catch (e) {
      // error to be handled
    }
  }
  if(bytes.length){
    console.log('****************');
    console.log(`key length: ${publicKey.length}`); // 451
    console.log('Bytes to be changed, and the verify would be valid');
    console.log(bytes.join(',')); // 49, 450
    console.log('****************');
  }

不同的公钥如何验证签名,我在这里遗漏了什么吗?

【问题讨论】:

    标签: node.js cryptography digital-signature


    【解决方案1】:

    因此,假设您显然使用了来自 RSA-2048 密钥对的 OpenSSL rsa -pubout,如果这是在 Unix 上的话:

    • PEM 文件中偏移量 49 处的字符对偏移量 16 和 17 处的部分字节进行编码(特别是偏移量 16 的底部 4 位和偏移量 17 的顶部 2 位)。这些是 2 字节的 NULL,表示 X.509 SubjectPublicKeyInfo 格式的 AlgorithmIdentifier 的参数部分。对于 RSA,没有算法参数(这就是编码使用 NULL 的原因),虽然这个字段仍然应该被解码,但也许 nodejs 不会费心这样做,因为知道它不需要并且会被忽略。

    • PEM 文件中偏移量 450 处的字符是终止页脚行的换行符。尽管格式定义需要,但实际上不需要解析它来提取文件的内容,即公钥 blob,也许 nodejs 不需要。

    【讨论】:

    • 感谢您的回答,有些事情不清楚。为什么当我将 hshinr 算法 sha256 更改为 sha512 时,例如我没有得到任何字节?
    • 如果您使用 sha512 签署 验证,您应该得到与 sha256 相同的结果。如果您使用一个哈希签名并使用另一个哈希进行验证,则无论使用的公钥是否有效,验证都会并且应该始终失败。如果您看到不同的内容,请在您的 Q 中添加细节(cmets 的大小和瞬态受到限制)。
    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2017-12-12
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多