Search code examples
pythonpython-3.xcryptographypublic-key-encryption

How to create JWKS public/private key pair in python?


How to create a JWKS public/private key pair, similar to the one that can be created manually at https://mkjwk.org/, that includes the Key ID (kid) and Key Use (use)? I used the cryptography module for generating a RSA key pair and python-jose for extracting the keys as JWK, but the created keys do not include kid and use (unsurprisingly, as they haven't been specified anywhere).

Code:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
​
from jose import jwk, constants
import json
​
key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = key.public_key().public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)
private_key = key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)
​
print(json.dumps(jwk.RSAKey(algorithm=constants.Algorithms.RS256, key=public_key.decode('utf-8')).to_dict()))
print(json.dumps(jwk.RSAKey(algorithm=constants.Algorithms.RS256, key=private_key.decode('utf-8')).to_dict()))

Generated public key by above code snippet (no kid or use properties):

{
    "alg": "RS256",
    "kty": "RSA",
    "n": "tqbcR_6JC....OKQ",
    "e": "AQAB"
}

Solution

  • I believe kid is just a piece of metadata (any string) that is not being used in the process of generating the key.

    In case of the use it is probably somewhat similar, though depending on the use you want different scheme for asymmetric cryptography (you can refer to the most well-known asymmetric cryptography system of RSA for both encryption and signing schemes' description).

    All in all, you can most probably recreate the exact structure of JSON adding appropriate keys to JSON dict based on the information above.