notes.dt.in.th

Generating keypairs for JWT

RS256

Using OpenSSL

openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem

Source: https://gist.github.com/ygotthilf/baa58da5c3dd1f69fae9?permalink_comment_id=2932501#gistcomment-2932501

Using Node.js with jose npm package

import { generateKeyPair } from 'jose'
const { publicKey, privateKey } = await generateKeyPair('RS256')
console.log(publicKey.export({ format: 'pem', type: 'spki' }))
console.log(privateKey.export({ format: 'pem', type: 'pkcs1' }))

Using Ruby (irb)

See Working with JWTs in Ruby for example. It only depends on the openssl gem which is bundled with Ruby.

In the browser as JWK

Run this in the browser console:

copy(
  await (async () => {
    const jose = await import('https://esm.run/jose')
    const pair = await jose.generateKeyPair('RS256', { extractable: true })
    return {
      privateKey: await jose.exportJWK(pair.privateKey),
      publicKey: await jose.exportJWK(pair.publicKey),
    }
  })()
)

Ed25519

Ed25519 keys are shorter.

Node.js

import { generateKeyPair } from 'jose'
const { publicKey, privateKey } = await generateKeyPair('EdDSA')
console.log(publicKey.export({ format: 'pem', type: 'spki' }))
console.log(privateKey.export({ format: 'pem', type: 'pkcs8' }))

In Deno REPL

let jose = await import('https://esm.run/jose')
let pair = await jose.generateKeyPair('EdDSA', { extractable: true })
console.log(await jose.exportSPKI(pair.publicKey))
console.log(await jose.exportPKCS8(pair.privateKey))