Reputation: 415
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
What is the correct way to generate a key with the given parameters?
What is the correct way to export a generated key in JSON format?
I come read from: SubtleCrypto MDN Web Docs
Upvotes: 1
Views: 6354
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