What is the secrets.token_hex() function in Python?

The secrets module is a comparatively new module which was introduced in Python 3.6. It generates cryptographically strong random numbers which can be used to generate security tokens, passwords, account authentication, etc.

The functions for generating secure tokens which are suitable for applications such as password resets, hard-to-guess URLs, etc., are also some of the features provided by the secrets module.

The secrets.token_hex() function is used to generate a random text string in hexadecimal that contains a given number of random bytes.

Parameters

The secrets.token_hex() function accepts a positive numeric value denoting the number of bytes generated in hexadecimal format. If no value is provided, a dynamic default value is used.

Return value

The secrets.token_hex() function returns the randomly generated hex-string of a specified number of bytes.

Code

The code below shows how the secrets.token_hex() method works in Python.

# Importing the secrets module
import secrets
# Creating tokens
token1 = secrets.token_hex()
token2 = secrets.token_hex(9)
# Printing tokens
print(token1)
print(token2)

Explanation

  • Line 2 imports the secrets module.

  • In line 5, the code creates the first token with no attribute provided.

  • In line 6, the code creates the second token with the size of 10 bytes.

  • Lines 9 and 10 print the output which is proper encrypted code.

In this way, you can generate a cryptographically secured hex-string of variable length using secrets.token_hex() function in Python.

Free Resources