Python secrets module — Token Generator

Abipravi
2 min readMay 29, 2021

Python supports vast number of inbuilt libraries for all the purposes like textprocessing, binary data processing, file and directory access and etc..

Now Let’s see about secrets module in python

Secrets module is used to generate secure random numbers for managing secrets.

The secrets modgraphiule is used for generating cryptocally strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
In particular, secrets should be used in pre

ference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Generating Tokens in Python

  1. secrets.token_bytes

secrets.token_bytes([nbytes=None])

Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used

token_bytes(16)

Output:

b’\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b

2. secrets.token_hex

secrets.token_hex([nbytes=None])

Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is None or not supplied, a reasonable default is used

token_hex(16)

Output:

f9bf78b9a18ce6d46a0cd2b0b86df9da’

3. secrets.token_urlsafe

secrets.([nbytes=None])

Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used

token_hex(16)

Output:

Drmhze6EPcv0fN_81Bj-nA’

Thanks for reading

--

--

Abipravi

Founder and CEO of Abipravi. Reactjs expert and Django developer. Intrested in artifical intellegence and Web development. Blogging and Teaching in youtube🔥🔥