Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 721
charliesneath Avatar asked Apr 08 '11 03:04

charliesneath


People also ask

How is a nonce generated?

A random nonce is produced by stringing arbitrary numbers together. A sequential nonce is produced incrementally. Using the sequential nonce method guarantees that values are not repeated, cannot be replayed and do not take up unnecessary space.

What is nonce in Python?

Introduction. A nonce is a number that uniquely identifies each call to the REST API private endpoints.

How do you generate a token in Python?

In order to authenticate a user connecting to an OpenTok session, a client must connect using a token (see this overview). Calling the generate_token() method returns a string. This string is the token.


2 Answers

While this probably does not exist at the time of this question creation, Python 3.6 introduced the secrets module which is meant for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In this case, generating a nonce can be generated easily (here a base64 encoded string):

nonce = secrets.token_urlsafe() 

Alternatives are token_bytes to get a binary token or token_hex to get an hexadecimal string.

like image 180
gabuzo Avatar answered Oct 24 '22 19:10

gabuzo


For most practical purposes this gives very good nonce:

import uuid uuid.uuid4().hex # 'b46290528cd949498ce4cc86ca854173' 

uuid4() uses os.urandom() which is best random you can get in python.

Nonce should be used only once and hard to predict. Note that uuid4() is harder to predict than uuid1() whereas later is more globally unique. So you can achieve even more strength by combining them:

uuid.uuid4().hex + uuid.uuid1().hex # 'a6d68f4d81ec440fb3d5ef6416079305f7a44a0c9e9011e684e2c42c0319303d' 
like image 33
andruso Avatar answered Oct 24 '22 21:10

andruso