python生成规定随机数,在Python中生成随机数的标准方法是什么?

博客围绕Python中为OAuth请求创建随机数展开,介绍了python - oauth2生成伪随机数的方法,还提及存在“make_nonce随机性不足”的问题及相应解决方案,如使用os.urandom或其抽象接口,最后给出了作者使用的lambda表达式生成随机数的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Can someone share the best practices for creating a nonce for an OAuth request in Python?

解决方案

Here's how python-oauth2 does it:

def generate_nonce(length=8):

"""Generate pseudorandom number."""

return ''.join([str(random.randint(0, 9)) for i in range(length)])

They also have:

@classmethod

def make_nonce(cls):

"""Generate pseudorandom number."""

return str(random.randint(0, 100000000))

Additionally there is this issue entitled: "make_nonce is not random enough", which proposes:

def gen_nonce(length):

""" Generates a random string of bytes, base64 encoded """

if length < 1:

return ''

string=base64.b64encode(os.urandom(length),altchars=b'-_')

b64len=4*floor(length,3)

if length%3 == 1:

b64len+=2

elif length%3 == 2:

b64len+=3

return string[0:b64len].decode()

And also references CVE-2013-4347. TL;DR version, use os.urandom or the abstracted interface to it (SystemRandom).

I like my lambdas—and didn't want non-alphanumeric characters—so I used this:

lambda length: filter(lambda s: s.isalpha(), b64encode(urandom(length * 2)))[:length]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值