繁体   English   中英

如何使用 window.crypto.subtle 验证 ES256(使用 P-256 和 SHA-256 的 ECDSA)签名?

[英]How to verify an ES256 (ECDSA using P-256 and SHA-256) signature with window.crypto.subtle?

我无法找出正确的参数来验证使用 web 加密中的 ECDSA P-256 公钥创建的 SHA-256 签名。 下面的脚本输出:

Node verify result: true
Web verify result: false

使用 web 加密进行验证的参数是什么? 我想我现在已经尝试了一切,除了正确的事情:|

(顺便说一句,在 Chrome 中尝试了 web 件,结果相同)

const crypto = require("crypto");
const webcrypto = require("node:crypto").webcrypto;

const derEncodedPublicKey = Buffer.from(
  "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE5/J6xKyJxzOJ85om+jUJUFHMqnpruqXnKx5jKRojB3E1gC29g/kAc6xHunY05IW+gn2oeAdjggnH7a4WQ8/Afg==",
  "base64"
);

const data = new Uint8Array([
  73, 150, 13, 229, 136, 14, 140, 104, 116, 52, 23, 15, 100, 118, 96, 91, 143,
  228, 174, 185, 162, 134, 50, 199, 153, 92, 243, 186, 131, 29, 151, 99, 5, 0,
  0, 0, 0, 182, 173, 217, 158, 122, 216, 45, 140, 214, 44, 204, 209, 62, 118,
  45, 12, 238, 10, 91, 88, 80, 235, 131, 5, 70, 171, 245, 252, 71, 13, 207, 235,
]);

const sig = new Uint8Array([
  48, 68, 2, 32, 58, 26, 13, 251, 116, 195, 219, 77, 90, 1, 64, 38, 54, 249, 56,
  87, 235, 24, 78, 26, 13, 88, 74, 224, 159, 58, 159, 133, 111, 98, 69, 214, 2,
  32, 87, 1, 32, 191, 170, 10, 33, 204, 86, 124, 73, 21, 153, 4, 58, 182, 248,
  175, 144, 80, 146, 173, 247, 205, 36, 51, 59, 221, 212, 133, 107, 118,
]);

function nodeVerify() {
  const nodeKey = crypto.createPublicKey({
    format: "der",
    key: derEncodedPublicKey,
    type: "spki",
  });
  const v = crypto.createVerify("SHA256").update(data);
  return v.verify(nodeKey, sig);
}

async function webVerify() {
  const webkey = await webcrypto.subtle.importKey(
    "spki",
    derEncodedPublicKey,
    {
      name: "ECDSA",
      namedCurve: "P-256",
    },
    false,
    ["verify"]
  );
  return webcrypto.subtle.verify(
    {
      name: "ECDSA",
      hash: "SHA-256",
    },
    webkey,
    sig,
    data
  );
}

(async () => {
  console.log("Node verify result:", nodeVerify());
  console.log("Web verify result:", await webVerify());
})().catch(console.error);

NodeJS 更简单,它需要更少的参数:)

谢谢你。

经过更多的谷歌搜索和尝试,我找到了答案:我使用的 ECDSA 签名实际上是一个 ASN.1 编码结构。 NodeJS 在验证过程中很好,但是 webcrypto 不是——它需要原始签名,这是 ASN.1 编码签名中 2 个整数的字节连接。

这篇文章中的更多信息: https://crypto.stackexchange.com/questions/57731/ecdsa-signature-rs-to-asn1-der-encoding-question

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM