How to generate an RSA key pair in Python
Generate an RSA public/private key pair in Python for RS256 JWT signing. Start with the browser RSA Key Generator for PEM output, or create keys with cryptography + PyJWT, then sign with the private key and verify with the public key — never commit private keys to git.
Last updated August 26, 2026
Steps
- 1
Open the RSA Key Generator and create a 2048-bit (or 4096-bit) key pair in your browser.
- 2
Copy the PEM private and public keys — generation is client-side; nothing is sent to a server.
- 3
In Python, load those PEMs (or generate with cryptography + PyJWT) and sign a test JWT using RS256.
- 4
Verify the token with the public key and an explicit algorithms: ['RS256'] allowlist.
- 5
Store the private key in a secrets manager or HSM; publish only the public key (or JWKS) to verifiers.
Code Example
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
import jwt
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem_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,
)
# Or load PEMs copied from the browser RSA Key Generator.
token = jwt.encode({"sub": "user-1"}, pem_private, algorithm="RS256")
payload = jwt.decode(token, pem_public, algorithms=["RS256"])Other languages
Related Articles
Frequently Asked Questions
Should I use 2048 or 4096-bit RSA for JWTs?
2048-bit is the standard for new RS256 deployments. Choose 4096-bit for long-lived roots or compliance mandates. Avoid 1024-bit keys.
How do I use generated RSA keys in Python?
Load the PEM private key to sign RS256 tokens and the PEM public key (or JWKS) to verify. With cryptography + PyJWT, always pin algorithms to RS256 so algorithm-confusion attacks fail.
Is browser RSA key generation safe?
Yes — keys are created with Web Crypto in your browser. Still treat the private key as secret: do not screenshot it into tickets or commit it.
When should I prefer RS256 over HS256?
Prefer RS256 when many services must verify tokens but only one should hold the signing key. HS256 is simpler when a single shared secret is acceptable.