'browserExtension: Why can I not export a key that has been generated in the background script in the content script?

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);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source