I’m trying to generate ECDSA keys using subtle crypto without any external libraries (it’s important to me), but getting “Cannot create a key using the specified key usages.” error. Can anyone advise on what’s wrong with the below approach?
async function generateECDSAKeyFromSeed(seed) {
// Convert the seed to an ArrayBuffer
const enc = new TextEncoder();
const seedBuffer = enc.encode(seed);
// Step 1: Derive key material from seed using PBKDF2
const baseKey = await crypto.subtle.importKey(
'raw',
seedBuffer,
{ name: 'PBKDF2' },
false,
['deriveBits', 'deriveKey']
);
const salt = crypto.getRandomValues(new Uint8Array(16)); // Random salt
const derivedBits = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256',
},
baseKey,
256
);
// Step 2: Import derived key material as a private key
const privateKey = await crypto.subtle.importKey(
'raw',
derivedBits,
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['sign']
);
// Step 3: Extract public key from private key
const publicKey = await crypto.subtle.exportKey('jwk', privateKey);
return {
privateKey: privateKey,
publicKey: publicKey
};
}
// Example usage
generateECDSAKeyFromSeed("your_seed_value").then(keys => {
console.log("Private Key:", keys.privateKey);
console.log("Public Key:", keys.publicKey);
}).catch(x => {
debugger;
console.error(x);
});