Skip to content
shellhacks.dev
Python

Generate a random password

Generate a random token with secrets.token_urlsafe. The argument counts bytes, not characters, so 16 bytes give a 22 character string, and random is not for this.

1 min read
Summarize in AI

You need a random password, API key or reset token, and random is the wrong module for it.

Python
import secrets, string

token = secrets.token_urlsafe(16)
print(len(token), set(token) <= set(string.ascii_letters + string.digits + "-_"))

alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(20))
print(len(password), password.isalnum())
Text
22 True
20 True

secrets draws from the operating system's secure random source, which is what the secrets documentation recommends for credentials. token_urlsafe(n) takes n random bytes and encodes them in base64 using only URL safe characters, so 16 bytes become 22 characters, and the check confirms the alphabet. secrets.choice picks uniformly from an alphabet you control, for a password with a fixed length.

The generated values are random, so the output only shows their length and character set. The random module is a predictable generator and must not make secrets. A token is only as long as its bytes: 16 bytes carry 128 bits, which is enough for a session or reset token. Store it hashed, not in plain text.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.