第一种:
# coding=utf-8 import re import string from binascii import hexlify as _hexlify BPF = 53 # Number of bits in a float RECIP_BPF = 2 ** -BPF def secure_random_int_list(a, b=None, length=1): """ 通过/dev/random生成length个安全的随机整数n,并保证均匀分布。 如果参数b非None,0 ≤ n < a(a必须大于0) 如果参数b为None,a ≤ n < b(b必须大于a) """ if b: begin = a end = b else: begin = 0 end = a # import random # random.SystemRandom() # import sys, os # os.urandom() width = end - begin assert width > 0, "please check: a > 0 or a < b" f = open("/dev/random", "rb") buff = f.read(length * 7) f.close() return [int((long(_hexlify(buff[i * 7: (i + 1) * 7]), 16) >> 3) * RECIP_BPF * width) + begin for i in range(length)] def secure_random_int(a, b=None): """ 通过/dev/random生成1个安全的随机整数n,并保证均匀分布。 如果参数b非None,0 ≤ n < a(a必须大于0) 如果参数b为None,a ≤ n < b(b必须大于a) """ return secure_random_int_list(a, b)[0] def secure_random_choice(allow_chars): """ 通过使用secure_random_int()随机选择 """ return allow_chars[secure_random_int(len(allow_chars))] def secure_random_string(allow_chars, length): """ 通过使用secure_random_int()方法生成指定长度的随机字符串 """ rands = secure_random_int_list(len(allow_chars), length=length) return "".join(allow_chars[rands[i]] for i in range(length)) def secure_random_password(length=15): """ 通过使用secure_random_int()方法生成指定长度的随机安全密码, 必然包含大写字母、小写字母、数字、特殊符号 """ def _verify_password(password): count = 0 if re.compile(r'[\W_]+').findall(password): count += 1 if re.compile(r'[a-z]+').findall(password): count += 1 if re.compile(r'[A-Z]+').findall(password): count += 1 if re.compile(r'[\d]+').findall(password): count += 1 return False if count < 3 else True assert length > 7 and length < 129, "password length is too long or too short (support 8~128)" while True: allow_clears = string.ascii_uppercase + string.punctuation + string.ascii_lowercase password = secure_random_string(allow_clears, length) if _verify_password(password): return password
第二种:
import os os.urandom(n=10)
第三种:
import random random.SystemRandom().random() random.SystemRandom().randint(1, 100) random.SystemRandom().uniform(1, 10) random.SystemRandom().randrange(1, 100)
浙公网安备 33010602011771号