# Generating public/private RSA key pair programmatically, using it for JWTs

In my app I'm using JSON Web Tokens for authentication purposes, using the pyjwt library. Instead of using static keys and/or worrying about key distribution, the server generates a public/private key pair upon startup itself and just keeps it in memory. The keys will be reset and thereby all existing tokens invalidated when the server restarts, which is fine for the intended use case. The key pair is generated using pycrypto.

The question is: am I generating and using the keys correctly, or is there any flaw which can lead to an exploit? Below is the general class which generates and validates all JWTs in my app:

from typing import NamedTuple
from datetime import datetime
import jwt
from Crypto.PublicKey import RSA

KeyPair = NamedTuple('KeyPair', [('public', str), ('private', str)])

class JWT:
def __init__(self, keypair: KeyPair=None, algorithm: str='RS256'):
self.keypair = keypair or self.generate_keypair()
self.algorithm = algorithm

@staticmethod
def generate_keypair() -> KeyPair:
key = RSA.generate(2048)
return KeyPair(public=key.publickey().exportKey('PEM').decode('ascii'),
private=key.exportKey('PEM').decode('ascii'))

def generate_token(self, payload: dict) -> str:

• The main goal of using JWTs is to keep other services stateless and reduce space complexity. If load balancing ever becomes an issue, I can think about distributing the keys among a bunch of JWT instances. – deceze Aug 5 '16 at 8:39