gpt4 book ai didi

javascript - native 加密加密抛出 DOMException

转载 作者:行者123 更新时间:2023-11-28 03:03:53 31 4
gpt4 key购买 nike

我正在使用 native-crypto 包,它是一个用于跨平台加密的 API(例如 web 和 node.js)。

let crypto = require("native-crypto");

我已经生成了公钥/私钥对...

keyPair = crypto.generate('P-256');

...我正在尝试像这样加密消息:

let message = "Hello, World!";
let encrypted = crypto.rsa.encrypt(keyPair.privateKey, message);

但是,这不起作用,我收到一个 DOMException (在浏览器环境中),没有更多详细信息。

如何解决这个问题?

可能的问题:

  • 也许我使用了不正确的函数组合
  • 这可能是因为我生成的 key 的 key_ops 仅包含 ["sign"],但不包含任何加密内容。

最佳答案

让我们从异常开始......由于某种原因,您没有看到错误消息。

Uncaught (in promise) DOMException: The required JWK member "kty" was missing

异步与同步

第一个错误是因为您尝试同步使用异步 API。

您需要在 keyPair 生成行添加 await 关键字:

keyPair = await crypto.generate('P-256');

如果没有 await 关键字,则会将 Promise 分配给 keyPair,而不是包含 kty 的对象。

key 类型错误

修复该问题后,您会看到另一个错误:

The JWK "kty" member was not "RSA"

这是因为 ECDSA key 与 RSA 加密一起使用。

还有一个问题

修复该问题后,您会看到另一个错误

The JWK "key_ops" member was inconsistent with that specified by the Web Crypto call. The JWK usage must be a superset of those requested

这件事我帮不上忙。我怀疑这是 native-crypto 的问题。您可能需要向他们的 github repo 提交错误报告。这是一个仅使用 Web Crypto API 的大致等效示例。

const crypto = window.crypto.subtle;

async function main() {
const keyPair = await crypto.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);

let message = "hello";

message = new TextEncoder().encode(message);
const encrypted = await crypto.encrypt({ name: "RSA-OAEP" }, keyPair.publicKey, message);

console.log(encrypted);
}

main()

关于javascript - native 加密加密抛出 DOMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779353/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com