Generating PEM encoded keys with OpenSSL

Generating PEM encoded keys with OpenSSL

While working on a small authentication microservice, I found myself needing to generate PEM encoded keys for use with jsonwebtoken.

Since my authentication middleware would require verifying the signature of the token using the pubkey, using a shared secret would not be possible.

I came across this gist by @maxogden which uses the jwa module, but can be adapted for the Auth0 jsonwebtoken module.

# RS256
# private key
openssl genrsa -out rs256-4096-private.rsa 4096
# public key
openssl rsa -in rs256-4096-private.rsa -pubout > rs256-4096-public.pem
# ES512
# private key
openssl ecparam -genkey -name secp521r1 -noout -out ecdsa-p521-private.pem
# public key
openssl ec -in ecdsa-p521-private.pem -pubout -out ecdsa-p521-public.pem
view raw index.sh hosted with ❤ by GitHub
// from npmjs.org/jwa. shout out to brianloveswords
const fs = require('fs');
const jwa = require('jwa');
const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem');
const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem');
const ecdsa = jwa('ES512');
const input = 'very important stuff';
const signature = ecdsa.sign(input, privateKey);
console.log('signature', signature)
console.log('verify', ecdsa.verify(input, signature, publicKey))
view raw test.js hosted with ❤ by GitHub

Published 18 Oct 2018

Thoughts on coding, crypto and other tidbits.
Aubrey Oosthuizen on Twitter