Last active
November 1, 2023 21:39
-
-
Save ctrlaltdev/6910513710ae1cc75ce2836dc688a801 to your computer and use it in GitHub Desktop.
Generate JWK key pair
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import crypto from 'crypto' | |
import { writeFileSync } from 'fs' | |
async function exportCryptoKeyToPEM(key) { | |
const exported = await crypto.subtle.exportKey('pkcs8', key) | |
const pemExported = `-----BEGIN PRIVATE KEY-----\n${Buffer.from(exported).toString('base64')}\n-----END PRIVATE KEY-----` | |
return pemExported | |
} | |
async function exportCryptoKeyToJWK(key) { | |
const exported = await crypto.subtle.exportKey('jwk', key) | |
return exported | |
} | |
const keyGenParams = { | |
name: 'ECDSA', | |
namedCurve: 'P-256', | |
} | |
const kid = crypto.createHash('sha1').update(crypto.randomBytes(16)).digest('hex') | |
const keyPair = await crypto.subtle.generateKey(keyGenParams, true, ['sign', 'verify']) | |
const pem = await exportCryptoKeyToPEM(keyPair.privateKey) | |
const jwk = await exportCryptoKeyToJWK(keyPair.publicKey) | |
jwk.kid = kid | |
jwk.alg = 'ES256' | |
jwk.use = 'sig' | |
delete jwk.key_ops | |
delete jwk.ext | |
writeFileSync(`./${kid}.pem`, pem) | |
writeFileSync('./jwk.json', JSON.stringify(jwk)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment