brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's secrets module makes tokens that are safe to use as passwords

Python
~/tips/tip-python-secrets-token-urlsafe

import secrets

Generate random tokens for API keys and passwords with the right kind of randomness.

If you generate an API token or a temporary password in Python, reach for secrets and leave random alone.

import secrets

print(secrets.token_urlsafe(32))   # e.g. 'q0x8...' safe in URLs and .env files
print(secrets.token_hex(16))       # 32 hex characters

if secrets.compare_digest(given_token, stored_token):
    print("ok")

The random module is built for simulations and games. Its output can be predicted once someone has seen enough of it. secrets uses the operating system’s secure random source, the same one /dev/urandom gives you.

The number you pass is bytes of randomness, not characters. token_urlsafe(32) gives 32 random bytes, encoded as about 43 characters of letters, digits, - and _. That alphabet means you can drop it into a URL, an environment file or a Docker Compose file without escaping anything.

I included compare_digest because it belongs with this. Comparing tokens with == can stop at the first wrong character, and in theory the timing leaks how much of a guess was right. compare_digest takes the same time either way. For a quick one off from the terminal, python3 -c 'import secrets; print(secrets.token_urlsafe(32))' works fine too.

Further reading: secrets module

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link