DEV Community

Cover image for Password generation with Python
natamacm
natamacm

Posted on

Password generation with Python

Passwords are everywhere. There are so many passwords, it's hard to keep track of them all without keeping some kind of record.

At the same time, "pass words" are no longer sufficient because of rainbow tables. That is why you need to generate passwords.

You could do that using the random module:

from string import punctuation, ascii_letters, digits
import random

def generate_password(pass_length):
    symbols = ascii_letters + digits + punctuation
    secure_random = random.SystemRandom()
    password = "".join(secure_random.choice(symbols) for i in range(pass_length))
    return password

password = generate_password(15)
print(password)

source: password generator

When generating random passwords, the default could be easily compromised. On the web they were told "I think you worry too much.". The secrets module was created to resolve this.

But if you use Python 3.6 and newer there's better way. The secrets module generates cryptographically safe passwords.

The secrets module lets you generate passwords:

import secrets
import string

alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(15))
print(password)

Latest comments (0)