What is the standard method for generating a nonce in Python?

前端 未结 5 1510
清歌不尽
清歌不尽 2021-02-12 12:48

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

5条回答
  •  失恋的感觉
    2021-02-12 13:19

    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]
    

提交回复
热议问题