Secret module – Generating secure random numbers:

Secret module comes handy when we need to generate random numbers in order to manage important data like passwords, security tokens, account details and other related secrets which are cryptographically strong. This module access to the most secure source of randomness. This module can be found in Python .6 and above and has high significance in data science.

Random numbers: class secrets.SystemRandom:

It is a class that uses os.urandom() function for generation of random numbers from the sources that are provide in the operating system.

  1. secrets.choice(sequence) – It is a function that returns a randomly chosen element from a non-empty sequence for managing a basic level of security.

Example 1: Generating a ten character alphanumeric password

Secret module - Secure random numbers in Python for Data Science

 Example 2: Generating a ten character alphanumeric password having at least one lowercase, one uppercase, and three digits.

Secret module - Secure random numbers in Python for Data Science

  1. secrets.randbelow(n) – It is a function that returns a random integer in the range of [0, n).
  2. secrets.randbits(k) – It is a function that returns an int with k random bits.Secret module - Secure random numbers in Python for Data Science
    Generation of tokens:

It is a module that provides several functions for generation of secure tokens for applications such as password resets, hard to guess URLs, etc.

  1. secrets.token_bytes([nbytes=None]) – It is a function responsible for generation of a random byte string containing nbytes number of bytes. In case no value is there, a reasonable default will be there.Secret module - Secure random numbers in Python for Data Science
  2. secrets.token_hex([nbytes=None]) – It is a function responsible for generation of random text string in hexadecimal containing nbytes random bytes. In case no value is there a reasonable default is there.
  3. secrets.token_urlsafe([nbytes=None]) – It is a function responsible for generation of random URL- safe text string containing nbytes random bytes. Also, it is suitable for using password recovery applications.

Example: Generating a hard to guess temporary URL containing a security token.

Note: We should use at least 32 bytes for tokens to secure against brute force attacks.

To learn more about random numbers in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.