对于一个项目,我需要一种创建数千个随机字符串同时保持较低冲突的方法。我正在寻找他们只有12个字符长和大写。有什么建议吗?
答案 0 :(得分:92)
<强> CODE:强>
from random import choice
from string import ascii_uppercase
print(''.join(choice(ascii_uppercase) for i in range(12)))
<强>输出:强>
5个例子:
QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD
修改强>
如果您只需要数字,请使用digits
常量,而不是ascii_uppercase
模块中的string
常量。
3个例子:
229945986931
867348810313
618228923380
答案 1 :(得分:14)
按Django
,您可以在get_random_string
模块中使用django.utils.crypto
功能。
get_random_string(length=12,
allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
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
示例:
get_random_string()
u'ngccjtxvvmr9'
get_random_string(4, allowed_chars='bqDE56')
u'DDD6'
但如果你不想Django
,here是它的独立代码:
代码:
import random
import hashlib
import time
SECRET_KEY = 'PUT A RANDOM KEY WITH 50 CHARACTERS LENGTH HERE !!'
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(),
SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
答案 2 :(得分:4)
可以制造发电机:
from string import ascii_uppercase
import random
from itertools import islice
def random_chars(size, chars=ascii_uppercase):
selection = iter(lambda: random.choice(chars), object())
while True:
yield ''.join(islice(selection, size))
random_gen = random_chars(12)
print next(random_gen)
# LEQIITOSJZOQ
print next(random_gen)
# PXUYJTOTHWPJ
然后只需在需要时从生成器中拉出来......在需要时使用next(random_gen)
,或者使用random_200 = list(islice(random_gen, 200))
...
答案 3 :(得分:1)
此函数生成具有指定长度的随机字符串大写字母
例如:长度= 6,将生成以下随机序列模式
<强> YLNYVQ 强>
import random as r
def generate_random_string(length):
random_string = ''
random_str_seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0,length):
if i % length == 0 and i != 0:
random_string += '-'
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
return random_string
答案 4 :(得分:0)
对于加密强的伪随机字节,您可以使用围绕OpenSSL的pyOpenSSL包装。
它提供bytes
函数来收集 bytes 的伪随机序列。
from OpenSSL import rand
b = rand.bytes(7)
BTW,12个大写字母比56位熵略多一点。您只需要读取7个字节。
答案 5 :(得分:0)
#!/bin/python3
import random
import string
def f(n: int) -> str:
bytes(random.choices(string.ascii_uppercase.encode('ascii'),k=n)).decode('ascii')
对于很大的n,运行速度更快。避免str连接。