There are a lot methods to generate and manage secrets such as passwords, account credentials, security tokens, and related secrets.

One of them is python’s built-in secrets module which is used for generating cryptographically strong random numbers suitable for managing secrets.

Let’s assume I want to generate a strong password for my user account:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import secrets

default_char_set = string.ascii_letters + string.digits + string.punctuation


def generate_key(length: int = 32, char_set: str = default_char_set):
    """Generate key from a character set with desired length

    Args:
        length (int): length of the key
        char_set (str): char_set to generate key from
    """
    return "".join(secrets.choice(char_set) for _ in range(length))


if __name__ == "__main__":
    import logging

    logging.basicConfig(level=logging.DEBUG)
    logging.info(generate_key())

Where ascii_* details are;

In [1]: string.ascii_letters
Out[1]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [2]: string.ascii_lowercase
Out[2]: 'abcdefghijklmnopqrstuvwxyz'

In [3]: string.ascii_uppercase
Out[3]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

In [4]: string.punctuation
Out[4]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

In [5]: string.digits
Out[5]: '0123456789'

If I run the module, I would get something like below:

$ python utils/secrets.py
INFO:root:tGs=d\%Q~Vp^<R_aS*D^0uUemRwX"&G-

You can remove string.punctuation or provide any subset of characters via char_set kwarg.

Info

As mentioned python’s documentation:

secrets should be used instead of default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

All done!