Skip to content

Instantly share code, notes, and snippets.

@facundopadilla
Last active March 6, 2023 14:49
Show Gist options
  • Save facundopadilla/94f6ceb9b08367e60b3aa1569a029610 to your computer and use it in GitHub Desktop.
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
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! :)
@facundopadilla
Copy link
Author

facundopadilla commented Mar 6, 2023

I use it in Pytest fixtures and is useful 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment