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"
}