Generate Secure Random Passwords and Tokens in Python

Generate Secure Random Passwords and Tokens in Python

Having secure random numbers allows us to manage sensitive information, such as password and security tokens. We will be using the secrets module, available in Python 3.6.

In this piece, you’ll learn the proper ways to generate strong random passwords and tokens that are cryptographically secured. Having secure random numbers allows us to manage sensitive information, such as password and security tokens. We will be using the secrets module, available since Python 3.6. The official documentation states:

“… secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.”

There are three sections in this article:

  1. Basic Usage
  2. Examples
  3. Conclusion

Let’s get started.

1. Basic Usage

The secrets module provides a few built-in functions that we can use to generate numbers and tokens. No setup is required but we need to import the module before we use it.

import secrets

Generate a random number

Use the randbelow function to generate a number. It accepts an integer and the number generated is between 0 and the input integer minus 1. The input integer must be higher than 0

secrets.randbelow(2) # generate either 0 or 1
secrets.randbelow(10) # generate a number from 0 to 9
secrets.randbelow(0) # error
secrets.randbelow(-10) # error

You can also use the randbits function to generate a random number. It accepts an integer which represents the number of bits. The input integer must be higher than 0.

secrets.randbits(1) # generate either 0 or 1
secrets.randbits(2) # generate a number from 0 to 3
secrets.randbits(4) # generate a number from 0 to 15
secrets.randbits(8) # generate a number from 0 to 255

Generate a random element from a list

The module also provides a way for us to choose a random element from a non-empty sequence. Let’s try it out using the choice function

colour = ['red', 'blue', 'green', 'purple', 'yellow']
secrets.choice(colour)

Generate a random byte string

token_bytes function is the perfect choice for generating bytes. You can specify an integer as a parameter. It will determine a random integer if you don’t specify anything.

secrets.token_bytes(8) # generate 8 random bytes string

You should see a random byte string like this:

b'\x1bq\x8e\x83\x08\xb2g\x17'
Generate a random string in hexadecimal

If you wanted a string in hexadecimal, you can use the token_hex function. Just like the token_bytes function, it accepts an integer which is used to generate n number of bytes, each byte will be converted to two hex digits later.

secrets.token_hex(16) # generate 16 random hexadecimal string

This is an example of the output:

cd7b7fb7e0c5c1fa17389050f884526e

Generate a URL-safe string

Sometimes, you might want a string that is Base64 encoded for your web application. The token_urlsafe function comes in handy for such a use case.

secrets.token_urlsafe(16)

I got the following result:

S357dE8QSuE
2. Examples

In this section, I will outline some of the best practices for generating a secure password and token. Feel free to test them on your own.

Generate a 10-characters alphanumeric password

import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(10))
print(password)
  • ascii_letters — contains both the lower case and upper case from A-Z

Generate a 10-characters hexadecimal password with punctuation

import string
import secrets
alphabet = string.hexdigits + string.punctuation
password = ''.join(secrets.choice(alphabet) for i in range(10))
print(password)
Generate a 10-characters password with at least one lowercase, one uppercase, and one digit
import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
    password = ''.join(secrets.choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password) and any(c.isupper() for c in password) and any(c.isdigit() for c in password)):
        break
print(password)
  • islower — Determine if the character is lowercase
  • isupper — Determine if the character is uppercase
  • isdigit — Determine if the character is a digit

Generate a 10-characters password with at least two uppercase and two digits

import string
import secrets
alphabet = string.ascii_letters + string.digits
while True:
    password = ''.join(secrets.choice(alphabet) for i in range(10))
    if (sum(c.isupper() for c in password) >= 2 and sum(c.isdigit() for c in password) >= 2):
        break
print(password)

Generate a four-word password that is unique

import secrets
animal = ['horse', 'elephant', 'monkey', 'donkey', 'goat', 'chicken', 'duck', 'mouse']
fruit = ['apple', 'banana', 'peach', 'orange', 'papaya', 'watermelon', 'durian']
electronic = ['computer', 'laptop', 'smartphone', 'battery', 'charger', 'cable']
vegetable = ['lettuce', 'spinach', 'celery', 'cabbage', 'turnip', 'cucumber', 'eggplant']
word_list = animal + fruit + electronic + vegetable
password = set()
while True:
    password.add(secrets.choice(word_list))
    if(len(password) >= 4):
        break
print(' '.join(password))
Generate a temporary URL with security tokens for a password reset
import secrets
url = 'https://mywebsite/reset?key=' + secrets.token_urlsafe()
print(url)
3. Conclusion

Let’s recap what we’ve learned today. We started off exploring the basic functions provided by the secrets module.

Then, we tested the functions to generate some random password and tokens in string token or bytes.

Finally, we tried to play with the module and generated a few different types of password that are strong and secured.

Please be reminded that you should not store your password in any plain text or encrypted file that is easily recoverable. They should be salted and hashed using an irreversible, one-way hash function.

Thanks for reading and hope you enjoyed this tutorial.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

Learn Python Programming

Learn Python Programming

Learn Python Programming

Description
Learn Python Programming

Learn Python Programming and increase your python programming skills with Coder Kovid.

Python is the highest growing programming language in this era. You can use Python to do everything like, web development, software development, cognitive development, machine learning, artificial intelligence, etc. You should learn python programming and increase your skills of programming.

In this course of learn python programming you don't need any prior programming knowledge. Every beginner can start with.

Basic knowledge
No prior knowledge needed to learn this course
What will you learn
Write Basic Syntax of Python Programming
Create Basic Real World Application
Program in a fluent manner
Get Familiar in Programming Environment