Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JWK from RSA Key pair?

Tags:

python

rsa

jwt

jwk

Suppose I have a python structure representing an RSA key pair as follows:

rsa_key_pair = {
    'private_key': '-----BEGIN PRIVATE KEY-----\nMIIEvAIBADAN__OBSCURED__qxu3sWAlY/bstTB5WfX8PA==\n-----END PRIVATE KEY-----\n',
    'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDCDDqGTiBYyoB9T5Haow5gcPBIIiltLVyM4vo8Txia1czgrk2XGH5t4dsWrcXIXjQafNb7PKelXZdRU36vIIAaZCZ0As5LtkC5D93+KO9PFLGkHxWi2G43naR9hOnrKliMjOd+JRUdApdY8c/wYJbDxGGuw7W9e3MsLABFEK+TnPTVJtO8Ix78FiuHRooWfU5ph7clfTeyundN2BNv8mO6ZSBiBAk6tN8Fwpljs96Z/3HnMQutX1/AFkMn5h+E0EV4CgLPvtRazfzoWNlIiXGmiVUVHrM1wna9jT/jyb7aoxkthkAXb6NNyCW/Znxq45Ozy27kZcw/X4WQ0QMmpgfX'
}

How can I write python code that will produce the JWK that can be used to verify JWT signed with this RSA private key? The Algorithm used is RSA256.

This website mkjwk accomplishes what I'm trying to do. But I'm trying to do it in python code.

like image 795
Saqib Ali Avatar asked Dec 26 '18 09:12

Saqib Ali


1 Answers

Here is an example of how you can use Authlib to dumps a JWK:

from authlib.jose import jwk

jwk.dumps(rsa_key_pair['public_key'], kty='RSA')
jwk.dumps(rsa_key_pair['private_key'], kty='RSA')

Here is the result of your public key:

{
  "kty": "RSA",
  "n": "wgw6hk4gWMqAfU-R2qMOYHDwSCIpbS1cjOL6PE8YmtXM4K5Nlxh-beHbFq3FyF40GnzW-zynpV2XUVN-ryCAGmQmdALOS7ZAuQ_d_ijvTxSxpB8VothuN52kfYTp6ypYjIznfiUVHQKXWPHP8GCWw8RhrsO1vXtzLCwARRCvk5z01SbTvCMe_BYrh0aKFn1OaYe3JX03srp3TdgTb_JjumUgYgQJOrTfBcKZY7Pemf9x5zELrV9fwBZDJ-YfhNBFeAoCz77UWs386FjZSIlxpolVFR6zNcJ2vY0_48m-2qMZLYZAF2-jTcglv2Z8auOTs8tu5GXMP1-FkNEDJqYH1w",
  "e": "AQAB"
}

via http://docs.authlib.org/en/latest/jose/jwk.html

like image 110
lepture Avatar answered Oct 18 '22 14:10

lepture