Skip to content

Instantly share code, notes, and snippets.

@bgth
Last active November 26, 2019 08:26
Show Gist options
  • Save bgth/9eaef46099cd3165edfc9e8bda73166c to your computer and use it in GitHub Desktop.
Save bgth/9eaef46099cd3165edfc9e8bda73166c to your computer and use it in GitHub Desktop.
Django's Generate Unique String
# https://github.com/django/django/blob/master/django/utils/crypto.py#L51
SECRET_KEY = "My Secret Key";
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(),
SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment