using more then one async() in a chain in the function breaks my function.
Is there a way i can include Key2pkcs8() inside generateKey() ?
async function generateKey() {
let getKeyPair = await crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384"
},
false,
["deriveKey"]
);
let PriKey = async() => {
let PriKey = await getKeyPair.privateKey;
console.log("pri = " + PriKey);
return PriKey;
};
let PubKey = async() => {
let PubKey = await getKeyPair.publicKey;
console.log("pub = " + PubKey);
};
let Key2pkcs8 = async(PriKey, PubKey) => {
let Key2pkcs8Pub = await crypto.subtle.exportKey("pkcs8", PubKey);
let Key2pkcs8Pri = await crypto.subtle.exportKey("pkcs8", PriKey);
return pkcs8keyarray = [Key2pkcs8Pub, Key2pkcs8Pri];
return Keyarray = [PriKey(), PubKey()]; // i want to put <return pkcs8keyarray()> here
};
generateKey().then(Key2pkcs8 => console.log(Key2pkcs8[0], Key2pkcs8[1])); works as expected and returns pri = [object CryptoKey] Promise { <state>: "fulfilled", <value>: undefined } Promise { <state>: "fulfilled", <value>: CryptoKey }
but when using return pkcs8keyarray() instead of return Keyarray = [PriKey(), PubKey()]; it breaks and returns undefined
i had intended to have key2pkcs2 take a key as a variable (public or private key) and then return both in a array at the end similar to the example
Your program demonstrates a misunderstanding of promises, async/await, the crypto module, and javascript as a whole.
letonly when you want to reassign values to a bindingreturn Keyarray = ...are leaking global variables and do not behave like you are probably expectingasyncfunction every time you want toawaitanother asynchronous valueconsole.logthe private or public keys. Per the exportKey docs, it returns a promise that resolves to an ArrayBuffer which is raw byte data and does not have a string representation.Since
generateKeyis returning an array pair of[private, public], we can easily use these in the other async functions you write -Move all side effects downstream in
.thenhandlers. Caller is responsible forcatching errors. Always handle errors -Do not try to implement cryptographic solutions if you do not understand these simple things. You will 100% get something wrong and you will introduce a vulnerability and you and your users will suffer the consequences.
Code in this answer is unttested and only here to highlight the mistakes I can readily see. Do not use the code verbatim and do not expect it to copy/paste it directly into your project. I do not understand what your requirements or intentions are and therefore cannot possibly make recommendations or offer other advice.
For more info on misuse of
asyncandawait, see this related Q&A.