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 lambda
s—and didn't want non-alphanumeric characters—so I used this:
lambda length: filter(lambda s: s.isalpha(), b64encode(urandom(length * 2)))[:length]