Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a cryptographically secure alphanumeric string in Python?

I'd like to generate alphanumeric authentication tokens in a cryptographically secure way on my Google App Engine Flask server. How can I go about doing that?

like image 353
brandones Avatar asked Sep 08 '25 10:09

brandones


1 Answers

Use PyCrypto, which implements a cryptographically secure version of python's random module. Google App Engine offers this as a library you can include in your App Engine project by adding the following to app.yaml:

libraries:
- name: pycrypto
  version: "2.6"

PyCrypto is also available outside GAE as a python library.

You can then generate a 32-character alphanumeric string with

from Crypto.Random import random

def generate_auth_token():
    """ Generate a 32-char alnum string. 190 bits of entropy. """
    alnum = ''.join(c for c in map(chr, range(256)) if c.isalnum())
    return ''.join(random.choice(alnum) for _ in range(32))
like image 75
brandones Avatar answered Sep 11 '25 02:09

brandones