DEV Community

Serhat Teker
Serhat Teker

Posted on β€’ Originally published at tech.serhatteker.com on

2

How to Create Secrets in Python

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:

# utils/secrets.py
#!/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())
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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-
Enter fullscreen mode Exit fullscreen mode

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

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!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay