Whats the simplest and safest method to generate a API KEY and SECRET in Python

Dhanushka Amarakoon picture Dhanushka Amarakoon · Jan 20, 2016 · Viewed 25.8k times · Source

I need to generate a API key and Secret that would be stored in a Redis server. What would be the best way to generate a key and secret?

I am develop a Django-tastypie framework based app.

Answer

Moby Duck picture Moby Duck · Jan 24, 2018

If you're on Python 3.6 or later, the secrets module is the way to go:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

e.g. to generate a 16 byte token:

>>> import secrets
>>> secrets.token_urlsafe(16)
'zs9XYCbTPKvux46UJckflw'
>>> secrets.token_hex(16)
'6bef18936ac12a9096e9fe7a8fe1f777'