在Python中生成随机数的标准方法是什么? [英] What is the standard method for generating a nonce in Python?

查看:181
本文介绍了在Python中生成随机数的标准方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以分享在Python中为OAuth请求创建随机数的最佳做法吗?

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

推荐答案

python-oauth2 做到了:

def generate_nonce(length=8):
    """Generate pseudorandom number."""
    return ''.join([str(random.randint(0, 9)) for i in range(length)])

他们也有:

@classmethod
def make_nonce(cls):
    """Generate pseudorandom number."""
    return str(random.randint(0, 100000000))

此外,此问题的标题为:" make_nonce不够随机" ,建议:

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()

还引用了 CVE-2013-4347 . TL; DR版本,请使用os.urandom或其抽象接口( SystemRandom ).

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

我喜欢我的lambda,并且不希望使用非字母数字字符,所以我使用了它:

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]

这篇关于在Python中生成随机数的标准方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆