javascript - native 加密加密抛出 DOMException

标签 javascript node.js encryption cryptography

我正在使用 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/

相关文章:

Javascript 十进制转二进制 - 64 位

javascript - 如何添加旧版本的 syntaxhighlighter

javascript - 使用 Jasmine 测试从 jQuery AJAX 回调调用的函数

javascript - passport.authenticate 超时,不知道为什么

javascript - 是否有任何 JavaScript 库可以读取 .cer 文件并从中获取 key ?

android - Android 4.4 可以支持 SHA256 密码吗?

javascript - 未捕获的类型错误 : Cannot read property 'init' of undefined on zTree_v3 library

javascript - node.js 和异步模块错误

node.js - npm 在 Windows 上设置了错误的 {prefix}

security - 散列密码和加密密码之间的区别