Skip to content

Instantly share code, notes, and snippets.

@glarrain
Created October 22, 2015 15:44
Show Gist options
  • Save glarrain/877f2facf0bd002829b0 to your computer and use it in GitHub Desktop.
Save glarrain/877f2facf0bd002829b0 to your computer and use it in GitHub Desktop.
Generate a 50-char random string, adequate for Django's `SECRET_KEY`
#!/usr/bin/env python
# coding: utf-8
"""Generate a 50-char random string, adequate for Django's ``SECRET_KEY``.
source: part of
https://github.com/django/django/blob/1.8.5/django/utils/crypto.py
"""
from __future__ import absolute_import, print_function, unicode_literals
import hashlib
import random
import time
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
# settings.SECRET_KEY,
'',
)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
def main():
# chars and length as defined in Django command 'startproject'
# https://github.com/django/django/blob/1.8.5/django/core/management/commands/startproject.py#L30
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars)
if __name__ == '__main__':
print(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment