← All notes

Python secrets generates secure tokens and passwords; use it instead of random for security

Answer: The secrets module provides functions for generating secure tokens, suitable for password resets, hard-to-guess URLs, and similar. Prefer secrets over the random module's default pseudo-random number generator, which is designed for modelling and simulation, not security.

Examples

import secrets, string

secrets.token_urlsafe(16)    # 'Drmhze6EPcv0fN_81Bj-nA'
secrets.token_hex(16)        # 32 hex digits

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

secrets.compare_digest(a, b) # constant-time compare

Functions

How long should tokens be

As of 2015, 32 bytes (256 bits) of randomness is believed sufficient for the typical use-case.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, secrets — Generate secure random numbers for managing secrets; Python PEPs, PEP 506 – Adding A Secrets Module To The Standard Library. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Public-Domain (https://peps.python.org/pep-0001/). PEP text is placed in the public domain (some also CC0-1.0). Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, secrets — Generate secure random numbers for managing secrets; Python PEPs, PEP 506 – Adding A Secrets Module To The Standard Library. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Public-Domain (https://peps.python.org/pep-0001/). PEP text is placed in the public domain (some also CC0-1.0).

Cite this

Permanent ID: iil:note:mntr72c9

iinventedlight. 2026. "Python secrets generates secure tokens and passwords; use it instead of random for security." iinventedlight Library, iil:note:mntr72c9, version of 2026-11-18. https://iinventedlight.com/library/notes/python-secrets/. License: CC-BY-4.0.

@misc{iil_note_mntr72c9,
  author = {{iinventedlight}},
  title = {{Python secrets generates secure tokens and passwords; use it instead of random for security}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-secrets/},
  note = {Permanent ID iil:note:mntr72c9. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-secrets.md.