How to Generate Safest API KEY in Python

From WikiHTP

Since a year or so until today, I have been involved in the development of multiple APIs and microservices, all of them duly protected with an API KEY or a token. But I have a little problem: whenever I start with a new one I never remember what is the simplest and safest way to generate a secret, a random string in hexadecimal or an API KEY in Python. That is why I have decided to create this tutorial which, even if it is short, will give you a quick site to come back to the next time you have a similar task. I hope it helps you too.

The simplest way to generate an API KEY in Python (<3.6)[edit]

Before Python 3.6, to generate a random string in hexadecimal to use as API KEY, we could use the "os" and "binascii" modules. For example, to generate a string of length 40, we just have to execute the following lines of code:

>>> import os, binascii 
>>> binascii. b2a_hex ( os. urandom ( 20 ))
b'd04ddec20a17281720d358069d203c5c9f632f96'

Discovering the secrets module in Python (3.6+)[edit]

The arrival of Python 3.6 brought with it the appearance of the module secrets. According to its own documentation, it is indicated that:

"The secrets module is used to generate cryptographically strong random numbers, suitable for managing data such as passwords, user authentication, security tokens and related secrets"

"In particular, secrets should be used preferentially over the generation of pseudo-random numbers using the random module, which is designed for modelling and simulation, not for security or cryptography"

To simulate the example seen in the previous section with the secrets module, just execute the following code:

>>> import secrets 
>>> secrets. token_hex ( 20 )
'e8bb10f809bfd1de83d6ea96e3630cc545dad1b3'

On certain occasions, we may want the secret to being part of a URL, for example, to reset a password. In that case, it is more appropriate to use the function token_urlsafe in the same way. This guarantees us that the generated characters are safe to use in a URL:

>>> secrets. token_urlsafe ( 20 )
'RwwrhCo2_uDRsMjZC2g2Aiqe9wg'

Keep in mind that the number passed in parentheses is not the length of the number of characters, but of bytes. In the case of the token_hex function, 1 byte corresponds to 2 hexadecimal digits. As for the token_urlsafe function, the returned string is Base 64 encoded, which is 1.3 characters per byte (although this is not always the case).

If the number of bytes to use is not specified, the secrets module will use a reasonable one by default (which can change at any time in future updates).

About This Tutorial

This page was last edited on 14 August 2020, at 07:12.