【问题标题】:How to verify an ES256 (ECDSA using P-256 and SHA-256) signature with window.crypto.subtle?如何使用 window.crypto.subtle 验证 ES256(使用 P-256 和 SHA-256 的 ECDSA)签名?
【发布时间】:2022-08-16 17:46:35
【问题描述】:

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

Node verify result: true
Web verify result: false

使验证也可以与网络加密一起使用的参数是什么?我想我现在已经尝试了一切,除了正确的事情:|

(顺便说一句,在 Chrome 中也尝试了网页,结果相同)

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 更简单,它需要更少的参数 :)

谢谢你。

    标签: javascript elliptic-curve webcrypto-api subtlecrypto


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 2019-02-12
      • 2019-08-15
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      相关资源
      最近更新 更多