What is the secrets.token_bytes() function in Python?
Functions to generate secure tokens that are suitable for applications such as password resets, hard-to-guess URLs, and so on are some of the features provided by the secrets module in Python.
The secrets.token_bytes() function in the secrets module is used to generate a random byte-string that contains a given number of bytes.
The
secretsmodule is a comparatively new module that was introduced in Python 3.6. Thesecretsmodule generates cryptographically strong random numbers that can be used to generate security tokens, passwords, account authentication, etc.
Parameters
The secrets.token_bytes() function accepts a positive numeric value that denotes the number of bytes to generate. If no value is provided, a dynamic default value is used.
Return value
The secrets.token_bytes() function returns the randomly generated byte-string of the specified number of bytes.
Code
Let’s take a look at the code.
# Importing the secrets moduleimport secrets# Creating tokenstoken1 = secrets.token_bytes()token2 = secrets.token_bytes(10)# Printing tokensprint(token1)print(token2)
Explanation
-
In line 2, we import the
secretsmodule. -
In line 5, we create the first token with no provided attribute.
-
In line 6, we create the second token with byte size 10.
-
In lines 9 and 10, we print the output, which we get as proper encrypted code.
In this way, we can generate cryptographically secured byte strings of variable length using the secrets.token_bytes() function in Python.