Generating RSA keys using openssh
The OpenSSH client package includes the ssh-keygen tool. While we know this tool can be used to generate keys for verifying SSH access to remote servers, it can also be used to generate RSA keys that can be used in python-jose (and other libraries) to verify the signature of JWTs.
The first step is to create an openssh key pair:
ssh-keygen -b 4096 -t rsa -f request_key -N ""
-N "" specifies we want a passwordless key.
This results in two files request_key and request_key.pub. If we look inside request_key we’ll see the first two lines look like this:
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAACFwAAAAdzc2gtcn
This OPENSSH format is not supported by python-jose or node-jose so we need to convert it to PKCS8 format:
openssl pkcs8 \
-topk8 \
-inform pem \
-in request_key \
-outform pem \
-nocrypt \
-out request_key.pkcs8
This command creates a new request_key.pkcs8 with the PKCS8 format of the OPENSSH key:
-----BEGIN PRIVATE KEY-----
MIIG/gIBADANBgkqhkiG9w0BAQEFAASCBugwggbkAgEAAoIBgQC214++HRrO1mZZ
...
Now the private key is in the correct format we turn our attention to the public key, request_key.pub:
ssh-rsa AAAAB3NzaC1yc2EAAAADA...
This is the OpenSSH public key format for use in the authorized_keys file on a remote server. However, it is not understood by JWT libraries and we must also convert this to PEM format:
openssl rsa -in request_key -pubout -out request_key.pub
This command overwrites the contents of the .pub file, and the first two lines now look like:
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAttePvh0aztZmWdQErGoX
...
The new private and public key can now be used by JWT libraries.