browserExtension:为什么我无法将后台脚本中生成的密钥导出到内容脚本中?

发布于 2025-01-11 20:58:41 字数 1159 浏览 0 评论 0原文

我正在研究浏览器扩展和网络加密 API。

当导出从后台脚本发送到浏览器扩展的内容脚本的密钥时,出现错误Argument 2 does not Implement Interface CryptoKey

我的假设是,这与 CryptoKey 无法使用非结构化克隆算法序列化或 CryptoKey 出于安全原因无法序列化有关,这是正确的吗?

无论如何,我可以将密钥保留在后台脚本中,所以我已经找到了问题的解决方案。不过,调试起来非常痛苦,所以我至少想知道失败的原因..

content-script.js:

window.addEventListener('click', async function() {
  console.log("start content script");
  let key = await browser.runtime.sendMessage({
    name: "AES-GCM",
  });
  console.log("key", JSON.stringify(Array.from(new Uint8Array(await crypto.subtle.exportKey('raw', key)))))
  console.log("key loaded");
})

console.log("content script loaded");

background-script.js:

console.log("background script started");
async function generateKey() { 
  console.log("generate key");
  let keySecret = crypto.getRandomValues(new Uint8Array(32));
  return await crypto.subtle.importKey(
    "raw",
    keySecret,
    "AES-GCM",
    true,
    ["encrypt"]
  );
}

function handler(message, sender, sendResponse) {
  return generateKey();
}

browser.runtime.onMessage.addListener(handler);

I'm playing around with browser extensions and the web crypto api.

When exporting a key that has been sent from the background script to the content script of my browser extension I get an error Argument 2 does not implement interface CryptoKey.

My assumption is that this has something to do with either CryptoKey not being serializable with the unstructured clone algorithm or CryptoKey not being serializable for security reasons, is this correct?

I could just keep the keys in the background script anyway, so I already have a solution to the problem. This has been quite painful to debug though, so I would at least like to know the reason this failed ..

content-script.js:

window.addEventListener('click', async function() {
  console.log("start content script");
  let key = await browser.runtime.sendMessage({
    name: "AES-GCM",
  });
  console.log("key", JSON.stringify(Array.from(new Uint8Array(await crypto.subtle.exportKey('raw', key)))))
  console.log("key loaded");
})

console.log("content script loaded");

background-script.js:

console.log("background script started");
async function generateKey() { 
  console.log("generate key");
  let keySecret = crypto.getRandomValues(new Uint8Array(32));
  return await crypto.subtle.importKey(
    "raw",
    keySecret,
    "AES-GCM",
    true,
    ["encrypt"]
  );
}

function handler(message, sender, sendResponse) {
  return generateKey();
}

browser.runtime.onMessage.addListener(handler);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文