Reputation: 7333
I have the following javascript. It should generate an ECDSA public-private keypair, and print BASE64 encoded public key as string to console. I would expect it to generate a new key on each reload. But it always prints the same all the time, and I do not understand why. Is it generating the very same key all the time? What to do to get a new key instead?
JSfiddle: https://jsfiddle.net/35bk4maw/
window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-256", //can be "P-256", "P-384", or "P-521"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["sign", "verify"] //can be any combination of "sign" and "verify"
)
.then(function(key)
{
window.crypto.subtle.exportKey(
"spki", //can be "jwk" (public or private), "spki" (public only), or "pkcs8" (private only)
key.publicKey //can be a publicKey or privateKey, as long as extractable was true
).then(function(keydata)
{
// this always prints something like "A21ixmVqdCBccnOheQJ1cmNlcl0="
// I would expect it to print different string on each reload!
console.log(btoa(keydata));
})
.catch(function(err){ console.error(err); });
}).catch(function(err){ console.error(err); });
Upvotes: 1
Views: 1397
Reputation: 7333
Finally I found what was wrong so I will answer my own question. The problem is that when btoa(keydata) is called, it does not understand the ArrayBuffer argument, so it computes BASE64 of keydata converted to string. And any ArrayBuffer converted to string is always "[ArrayBuffer Object]". Thus the base64 encoded result of this string is always W29iamVjdCBBcnJheUJ1ZmZlcl0=
So in order for me to print the ArrayBuffer contents in some readable form, I need to use different way how to encode it, this answer helped me to print just HEX of the public key: Javascript ArrayBuffer to Hex
Upvotes: 2