Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Use secrets.token_hex() function in Python

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.

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring