Can you believe it? People use unknown and potentially insecure websites to generate their random passwords!
This works as follows: A website generates a “random” password for them and they copy&paste it and assume this is a safe password because of the randomness of the characters. What a security flaw! Why? Because the website could store the password instead of forgetting it—or the password could be accessed by a third party (“man-in-the-middle attack”) between you and the password-generating webserver!
This article shows you how to code your own Python single-line password generator that generates random sequences securely on your computer. This is a secure, reliable way to generate your safe passwords in a single line of Python code.
So, let’s get started!
Problem: Generate random passwords of size
n in a single line of Python code.
Example: You may want to create a password with a length of 10 characters.
Calling your password generator another time may return the following:
Each subsequent call returns a random sequence of 10 characters. This way, you can create random passwords that are hard to guess! And you don’t have to trust a web-based password generator (that may store your generated passwords).
Method 1: Choice Function from Random Module
from random import choice; print(''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for i in range(10)]))
The code consists of the following parts:
- You import the
choice()function from the
randommodule to access a random element from a sequence.
- You pass the string
'abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)'into it to obtain a random character (including some special chars).
- You run this character selection routine
n=10times in a list comprehension statement to generate 10 random characters.
- You join together the
n=10characters in the generated list to create a string with 10 characters.
- You print the result to the shell.
Here it is — your newly created password!
Note: As an alternative, you can also call this one-liner from your operating system using the
-c flag of the
$ python -c "from random import choice; print(''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)') for i in range(10)]))"
CAVEAT: Using a Simple Phrase May Be More Secure! 🙂
You may know the popular web comic xkcd. Here’s one excellent observation about password strengths:
You can measure password strengths with Entropy. Here’s a relevant quote from Wikipedia:
It is usual in the computer industry to specify password strength in terms of information entropy which is measured in bits and is a concept from information theory. Instead of the number of guesses needed to find the password with certainty, the base-2 logarithm of that number is given, which is commonly referred to as the number of “entropy bits” in a password, though this is not exactly the same quantity as information entropy. A password with an entropy of 42 bits calculated in this way would be as strong as a string of 42 bits chosen randomly, for example by a fair coin toss. Put another way, a password with an entropy of 42 bits would require 242 (4,398,046,511,104) attempts to exhaust all possibilities during a brute force search. Thus, by increasing the entropy of the password by one bit the number of guesses required doubles, making an attacker’s task twice as difficult. On average, an attacker will have to try half the possible number of passwords before finding the correct one.
Method 2: Random Randint
A similar but slightly different one-liner is the following:
import random as r; c = 'abcdefghijklmnopqrstuvwxyz0123456789%^*(-_=+)'; print(''.join([c[r.randint(0,len(c)-1)] for i in range(10)]))
The idea is similar but with one difference: you use indexing with a random index on the string of characters
c to find a single random character. The rest is pretty much the same.
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.