Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

Build a Secure Password Generator in Python with `secrets`

Use Python’s secrets module to generate configurable character passwords or word-based passphrases, and understand how generation differs from storing account passwords.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s secrets module—not random—to generate passwords intended for real accounts. The standard library lets you choose individual characters from an alphabet or words from a list; you decide the length and any destination-specific rules.

Why use secrets instead of random?

Python’s official documentation for secrets describes it as a source of cryptographically strong random values suitable for passwords and authentication secrets. It says to prefer secrets over the default pseudo-random generator in random, which is designed for modelling and simulation, not security or cryptography.

As an Amazon Associate I earn from qualifying purchases.

That distinction matters when a generated value must be difficult to guess. Use random for simulations or other non-security tasks; use secrets for password characters, passphrase words, and similar secrets.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate a password from a character alphabet

Choose an alphabet containing the characters you want to allow, then call secrets.choice once for each position. This example lets you set the length and whether the generator includes lowercase letters, uppercase letters, digits, or punctuation.

import secrets
import string


def generate_password(length=20, *, lowercase=True, uppercase=True,
                       digits=True, punctuation=False):
    alphabet = ""
    if lowercase:
        alphabet += string.ascii_lowercase
    if uppercase:
        alphabet += string.ascii_uppercase
    if digits:
        alphabet += string.digits
    if punctuation:
        alphabet += string.punctuation

    if not alphabet:
        raise ValueError("Enable at least one character set")
    if length < 1:
        raise ValueError("Length must be at least 1")

    return "".join(secrets.choice(alphabet) for _ in range(length))


print(generate_password(length=24, punctuation=True))

The function samples each character independently from the selected alphabet. Its switches define what may appear, not what must appear: for instance, enabling uppercase letters does not guarantee that the result contains one. If a destination requires at least one character from particular categories, add a check-and-regenerate step or construct the password to meet those requirements before securely shuffling it.

Match the password to the destination

Length and allowed characters are choices for your implementation, not universal policy rules. Check the destination’s current requirements before generating a value. Some services reject particular punctuation or impose limits; an alphabet that includes characters the destination refuses can make the result unusable.

  • Length: Set it to a value accepted by the destination. The eight-character example in the Python documentation is a code example, not a universal recommendation.
  • Character categories: Enable only the sets the destination accepts, and enforce any mandatory categories explicitly.
  • Output handling: A generator that prints a password displays it in the terminal. Avoid leaving the value in shared logs, screenshots, or other exposed output.

Generate a word-based passphrase

A passphrase selects several words independently from a word list. It can be easier to remember or type than a string of mixed characters, though whether a particular service accepts spaces or long phrases depends on that service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import secrets

words = ["amber", "birch", "cobalt", "dawn", "ember", "fable",
         "garden", "harbor", "island", "juniper", "lantern", "meadow"]


def generate_passphrase(word_count=5):
    if word_count < 1:
        raise ValueError("Word count must be at least 1")
    return "-".join(secrets.choice(words) for _ in range(word_count))


print(generate_passphrase())

This small list illustrates the method; it is not a security standard. For a real passphrase generator, use a sufficiently large, well-chosen word list and select each word with secrets.choice. The number of independently selected words and the size of the list determine how many possible combinations the generator can produce. The Python documentation demonstrates word selection but does not establish a universal word count or strength table.

Choose between a character password and a passphrase

Consideration Character password Word-based passphrase
Selection Choose characters from an allowed alphabet with secrets.choice. Choose words from a word list with secrets.choice.
Destination compatibility Depends on accepted length and allowed characters. Depends on accepted length, separators, and whether spaces or punctuation are permitted.
Usability May be harder to remember or type when long and varied. May be easier to remember or type, depending on the words and format.
Best fit Useful where the service accepts a specified set of characters or where a compact generated value is needed. Useful when a longer, word-based value is accepted and easier recall matters.

For a machine token rather than a password a person needs to enter, the secrets module also provides token-generation functions. Its documentation says that, as of 2015, 32 bytes (256 bits) of randomness was believed sufficient for the typical use case expected for the module. That dated qualification is not a password-length rule: the documentation also warns that the default token entropy may change, including in maintenance releases. Consult the current documentation and choose deliberately when generating tokens.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Generating a password is different from storing one

A local script that creates and displays a new password is not the same as an application that accepts and stores account passwords. Python’s documentation warns that applications should not store passwords in recoverable form, whether plaintext or encrypted; it recommends salted, cryptographically strong one-way hashing for stored account passwords. A generated password should not be saved as recoverable account data by an application.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.