LT-Sites
LT-Sites

Reputation: 415

How to correctly implement Web Crypto API generateKey and exportKey?

Hello everyone!

I have this code:

async function generateKey() {
  const algoritm = { name: "AES-CBC", length: 256 };
  const exportable = true;
  const usage = ['encrypt'];
  return await window.crypto.subtle.generateKey(algoritm, exportable, usage).then(key => { return key; 
  });
}

when I call console.log(generateKey ()); I get: >Promise at first load and >Promise {<pending>} when update browser window.

async function exportKey(key) {
  const format = "jwk";
  return await window.crypto.subtle.exportKey(format, key).then(key => { return key; });
}

when I call let key =generateKey(); console.log(exportKey (key)); I get: 'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

I have two questions about

I come read from: SubtleCrypto MDN Web Docs

Upvotes: 1

Views: 6354

Answers (1)

richytong
richytong

Reputation: 2452

Your API usage looks correct. You are getting the error 'SubtleCrypto': parameter 2 is not of type 'CryptoKey' because parameter 2 is of type Promise. To fix this issue, resolve the promise from generateKey before passing it to exportKey

const main = async () => {
  const key = await generateKey()
  const exported = await exportKey(key)
  console.log(exported)
}

Of course, this can get even simpler if you use my library, rubico

const { pipe } = require('rubico')

const main = pipe([generateKey, exportKey, console.log])

The two examples are equivalent.

Upvotes: 3

Related Questions