Pure Python exemple:
import string
import random
def random_string(lenth=10):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
Ref.:
https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
If you are using Django, it ready to use in crypto module:
from django.utils.crypto import get_random_string
The raw code:
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return 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()
).digest()
)
return ''.join(random.choice(allowed_chars) for i in range(length))
Nenhum comentário:
Postar um comentário