Last active
March 6, 2023 14:49
-
-
Save facundopadilla/94f6ceb9b08367e60b3aa1569a029610 to your computer and use it in GitHub Desktop.
Generate RSA private and public key in Python on memory for JWT tokens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, timedelta, timezone | |
from jose import jwt # or import jwt | |
from cryptography.hazmat.primitives import serialization | |
from cryptography.hazmat.primitives.asymmetric import rsa | |
from cryptography.hazmat.backends import default_backend | |
# --- Generate private and public key --- | |
key = rsa.generate_private_key( | |
backend=default_backend(), | |
public_exponent=65537, | |
key_size=2048 | |
) | |
private_key = key.private_bytes( | |
encoding=serialization.Encoding.PEM, | |
format=serialization.PrivateFormat.PKCS8, | |
encryption_algorithm=serialization.NoEncryption() | |
).decode() | |
public_key = key.public_key().public_bytes( | |
encoding=serialization.Encoding.PEM, | |
format=serialization.PublicFormat.SubjectPublicKeyInfo | |
).decode() | |
# --- Generate encoded JWT token --- | |
claims = { | |
"sub": "Subject of the payload", | |
"exp": datetime.now(tz=timezone.utc) + timedelta(hours=1) # expire in 1 hour, f.e. | |
} | |
encoded = jwt.encode( | |
claims=claims, | |
algorithm="RS256", | |
key=private_key | |
) | |
# --- Verify token --- | |
decoded = jwt.decode( | |
token=encoded, key=public_key, algorithms="RS256" | |
) | |
# Enjoy! :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use it in Pytest fixtures and is useful 👍