browserExtension:为什么我无法将后台脚本中生成的密钥导出到内容脚本中?
我正在研究浏览器扩展和网络加密 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论