Skip to content

Instantly share code, notes, and snippets.

@ctrlaltdev
Last active November 1, 2023 21:39
Show Gist options
  • Save ctrlaltdev/6910513710ae1cc75ce2836dc688a801 to your computer and use it in GitHub Desktop.
Save ctrlaltdev/6910513710ae1cc75ce2836dc688a801 to your computer and use it in GitHub Desktop.
Generate JWK key pair
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