Python Secret Module | Generate Secure Random Numbers

In this tutorial, we will learn about one of the interesting Python modules, named as secret. We will also learn its methods and how it is different from the random module. It was released in Python 3.6 and is popularly known to generate data close to true randomness. We will learn how to implement the secrets.SystemRandom() class and secrete module function. Before diving deep into this topic, let's briefly introduce the secret module.

Introduction to secrete Module

Python secrete module is available in Python 3.6 or above version. It is used to generate random numbers for managing essential data such as passwords, account authentication, security tokens, and related secrets. We can produce cryptographically robust data, and the produced data can be used in the OTP (One Time Password).

Below is some critical usage of standard security-related functions.

  • Generating random numbers.
  • Creating password and OTP.
  • Random token
  • Password recovery safe URLs and session keys.

Reason for Using secrete module in place of the random module

Random module also can generate random data, which is not non-deterministic data. In other words, data generated by the random module can be determined easily by finding the seed used to produce the data. It is not suitable for security purposes. On the other hand, the secrets module is an excellent way to produce secure data. The secret module is a cryptographically strong Pseudo-Random Number Generator useful in security-sensitive applications.

Now, let's learn its essential methods.

Class secrets.SystemRandom

This class is used to generate secure random numbers using the highest-quality sources provided by the operating system. It allows us to use all functions of the random module. The random module has the same class random.SystemRandom is used to generate cryptographically secure random data.

Let's understand how to use secrets.SystemRandom class to secure the random generator.

Example -

Output:

Some Random Integers: 57
Secure Random Intergers within Given Range: 12
The List of Random Numbers: 48
Secure Random Sample: [48, 54, 28]
Secure Float Number: 24.693838143278885

The secrets.choice(sequence) Method

It is a method of secrets.SystemRandom class and it returns the randomly-chosen element from the given non-empty sequence. Let's understand the following example.

Example -

In the below example, we will generate the eight characters alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.

Output:

The Random Password is: 7Jfb7er2

The randbelow(n) Method

This function is used to generate the secure integer number from the given range 0 to n. Here n is the exclusive upper bound. Let's understand the following example.

Example -

Output:

13, 13, 1, 9, 6,

The randbits(K) Method

This method returns a secure unsigned integer with k random bits. It is used to generate a random bitmask that would consist of N bit set. The generated numbers are more secure than the randbelow numbers.

It generates a random integer within a bit range.

  • If k=4, then unsigned integer from 0 to 15.
  • If k=8, then unsigned integer from 0 to 255.
  • If k=16, then unsigned integer from 0 to 65, 535, and so on.

Let's understand the below example.

Example -

Output:

The 4 bit number: 11
The 8 bit number: 170
The 16 bit number: 38967
The 32 bit number: 1901293963

Generate Secure Tokens using secrets Module

This module facilitates us to generate the secure token using several methods. It is helpful for applications to generate reset password tokens and hard-to-guess URLs. We will use the following function to generate the tokens.

  • token_bytes([nbytes=None]) - It generates the random byte string containing nbytes numbers of bytes. If no value is provided, a reasonable default is used.

Example -

Output:

b'\x07w\xe0b\xd0\xae\xb8k\x91\x95n\xbc\x04X\xbc\x8e\x03\xcd\xc5]&.]\xda\x8b*\x9d\x1d)m\x18['
b'\xfc\xdd\xaa\xe9\x8f\xa3\x96\x81\x84s\xc7\xcbw\xc7\xc05\xbc\xa6J\xbe'
  • token_hex([nbytes=None]) - It generates a random string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used. Let's understand the following example.

Example -

Output:

ef38a198fd6f5b61c3fbe7af84f6e5702a7e76c3ecca5f30008e
2ea433c452ba4a96ddc96be7
  • token_urlsafe([nbytes=None]) - It returns the secure random URL-safe text string, containing n-bytes random bytes. Sometime we need a secure link for some data transaction or password reset. We can pass the require bytes as attributes. Let's understand the following example.

Example - Generate the hard-to-guess temporary URL containing a security token.

Output:

https://mywebsite.com/reset=w0Ts0Wm6gxg

The token should be used 32 bytes for the tokens to be secure against the brute-force attack. We should use the byte size as per our requirements. The secrete module provides the compare_digest(a,b) function to reduce the risk of timing attacks.

Practical Implementation of secrets Module

Let's create a program where we generate the password and send created password to the temporary hard-to-guess URL. So that client can reset the password using the URL.

Example -

Output:

Secure pswd is:  Tm/|M^6V{>
You can reset your password using Reset URL Link
https://users.com/user/sam/reset=17eCrjnQ6RI05EVZeLSzK9ujuc84PiO1LTd--0BdKW0

Explanation -

In the above code, we have generated the ten-character password that consists of at least one lowercase character, at least one digit, and one special character. To do we have used the choice() methods and added into the pswd variable. Then we generated the temporary URL.

Conclusion

This tutorial has covered essential concepts of the secrets module and its several methods. We have also implemented those functions using Python code, and the python secrets module helps us generate secure passwords and secret URLs or tokens.






Latest Courses