I need to generate a deterministic set ECDSA
keys using zero dependencies javascript
, for which I produce a pkcs8
key out of raw bytes and then importe it as ECDSA
private key. Is this logically possible and if so what’s wrong with the code below, as it gives me DataError error during the import call.
// Example function to convert derived bits to a PKCS#8 formatted key and import it
function convertRawKeyToPKCS8(rawKey, curveOid) {
// PKCS#8 header for ECDSA with the chosen curve OID
const pkcs8Header = [
0x30, 0x81, 0x87, // SEQUENCE (header, total length)
0x02, 0x01, 0x00, // INTEGER (version 0)
0x30, 0x13, // SEQUENCE (AlgorithmIdentifier header)
0x06, 0x07, // OBJECT IDENTIFIER (1.2.840.10045.2.1 - ecPublicKey OID)
0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
0x06, 0x08, // OBJECT IDENTIFIER for curve (this is curve specific, provided as parameter)
...curveOid,
0x04, 0x6d, // OCTET STRING (privateKey length follows)
0x30, 0x6b, // SEQUENCE
0x02, 0x01, 0x01, // INTEGER (version 1)
0x04, 0x20 // OCTET STRING (private key length, 32 bytes for P-256)
];
// Append the raw private key bytes
const pkcs8Key = new Uint8Array(pkcs8Header.length + rawKey.length);
pkcs8Key.set(pkcs8Header);
pkcs8Key.set(rawKey, pkcs8Header.length);
return pkcs8Key;
}
// Example OIDs for different elliptic curves:
const OID_P256 = [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]; // P-256 curve OID
// Example raw ECDSA private key for P-256 (32 bytes):
const rawPrivateKey = new Uint8Array([
0x93, 0x6a, 0x62, 0x91, 0x62, 0xa9, 0xba, 0x46,
0x0c, 0x12, 0xfa, 0xb7, 0xdb, 0xe0, 0x2f, 0x91,
0x52, 0xfa, 0xd2, 0xda, 0x47, 0x9a, 0x7d, 0xf2,
0xbe, 0xab, 0xaa, 0x04, 0x48, 0x67, 0x6b, 0xa1
]);
// Generate the PKCS#8 key
const pkcs8Key = convertRawKeyToPKCS8(rawPrivateKey, OID_P256);
// Log the resulting PKCS#8 key as a hexadecimal string for display (optional)
console.log(Array.from(pkcs8Key).map(b => b.toString(16).padStart(2, '0')).join(''));
// Use the SubtleCrypto API to import the PKCS#8 key
async function importECDSAPrivateKey(pkcs8Key) {
const privateKey = await crypto.subtle.importKey(
"pkcs8",
pkcs8Key.buffer,
{
name: "ECDSA",
namedCurve: "P-256",
},
true, // Extractable
["sign"] // Key usage
);
return privateKey;
}
// Example usage
importECDSAPrivateKey(pkcs8Key).then(privateKey => {
console.log('Private key imported:', privateKey);
}).catch(console.error);