Untitled
unknown
plain_text
a year ago
2.0 kB
6
Indexable
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend import base64 import json import hashlib def generate_rsa_key_pair(): # Generate private key private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) # Extract public key from private key public_key = private_key.public_key() # Convert the keys to PEM format pem_private_key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) pem_public_key = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) return pem_private_key, pem_public_key private_key, public_key = generate_rsa_key_pair() def generate_kid(public_key_pem): # Generate a SHA-256 hash of the public key sha256 = hashlib.sha256() sha256.update(public_key_pem.encode()) return base64.urlsafe_b64encode(sha256.digest()).decode('utf-8').rstrip('=') kid = generate_kid(public_key.decode('utf-8')) def rsa_public_key_to_jwk(public_key): # Convert the public key to a JWK public_key_numbers = public_key.public_numbers() e = base64.urlsafe_b64encode(public_key_numbers.e.to_bytes(3, byteorder='big')).decode('utf-8').rstrip('=') n = base64.urlsafe_b64encode(public_key_numbers.n.to_bytes(256, byteorder='big')).decode('utf-8').rstrip('=') jwk = { "keys": [ { "kty": "RSA", "use": "sig", "n": n, "e": e, "kid": "test", "alg": "RS256" } ] } return jwk public_key_obj = serialization.load_pem_public_key(public_key, backend=default_backend()) jwk = rsa_public_key_to_jwk(public_key_obj) print(json.dumps(jwk, indent=4))
Editor is loading...
Leave a Comment