Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 149 ยท Beyond the Basics

Secure Python: Secrets, Hashing and Injection

Write safer Python. Generate tokens with secrets, hash and verify passwords, sign data with hmac, avoid pickle risks, and stop SQL and command injection.

Most security bugs are not clever hacks. They are ordinary programs that trusted something they should not have: a random number that was predictable, a password stored in plain text, a string pasted into a SQL query, a file loaded with pickle. Python's standard library already contains the safe versions of each tool, so the main skill is knowing which one to reach for.

In this lesson you will generate unguessable tokens with secrets, hash data and passwords with hashlib, sign and verify messages with hmac, understand why pickle is dangerous, and defend against SQL and command injection. The examples run in the editors; they use safe stand-ins, so nothing here can harm your machine. This is an introduction, not a complete security course: when you protect real users, follow the security guidance of your framework and keep dependencies updated.

Random numbers: random versus secrets

The random module produces numbers that look random but come from a predictable formula. If an attacker sees enough outputs, they can work out the rest. That is fine for shuffling a playlist and dangerous for anything an attacker must not guess: password-reset links, session IDs, API keys, one-time codes.

For these, use the secrets module, which draws from the operating system's secure random source:

Function Returns
secrets.token_hex(n) a string of 2*n hexadecimal characters from n random bytes
secrets.token_urlsafe(n) a URL-safe string from n random bytes (about 1.3*n characters)
secrets.token_bytes(n) n random bytes
secrets.choice(seq) one random element
secrets.randbelow(n) a random integer from 0 to n-1
secrets.compare_digest(a, b) compares two strings or bytes in constant time
Python Generate secure tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output is deliberately limited to facts that are always the same (lengths and checks), because the tokens themselves change on every run. Use at least 16 random bytes (128 bits) for anything that grants access.

Hashing with hashlib

A hash function turns any input into a fixed-length "fingerprint". The same input always gives the same hash, a tiny change gives a completely different hash, and you cannot (feasibly) get back to the input. hashlib provides SHA-256, SHA-3, BLAKE2 and others:

Python Fingerprints with hashlib

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hashes take bytes, so encode text first ("text".encode("utf-8")). SHA-256 is a good default for integrity checks, such as confirming that a downloaded file matches its published checksum. MD5 and SHA-1 are broken for security purposes (attackers can craft collisions); use them only for non-security checksums.

Never store passwords with a plain hash

A fast hash like SHA-256 is the wrong tool for passwords. Attackers can try billions of guesses per second against stolen hashes, and identical passwords produce identical hashes. A password hash must be slow on purpose and salted, which means a unique random value is mixed in for every user. The standard library offers hashlib.pbkdf2_hmac and hashlib.scrypt. Together with hmac.compare_digest they make a complete scheme:

Python Salted, slow password hashing (PBKDF2)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The short if not hasattr(...) block at the top exists only because the Python that runs in your browser has no hashlib.pbkdf2_hmac; on your own computer you can delete it. The stored string carries its own salt and iteration count, so you can raise the cost later. In a real application use a well-reviewed password-hashing library (Argon2 via argon2-cffi, or bcrypt) or the one built into your web framework, and let it handle storage format and upgrades. Never invent your own scheme; the example shows how the parts fit together.

Signing messages with hmac

Sometimes the data is not secret but must not be altered: a cookie that says user=42, a webhook payload, a download link. An HMAC combines the message with a secret key to produce a tag. Anyone without the key cannot forge a valid tag for a changed message.

sequenceDiagram
    participant S as Server (has secret key)
    participant C as Client
    S->>C: message + HMAC(key, message)
    C->>S: message + tag (maybe modified)
    S->>S: recompute HMAC(key, message)
    alt tags match (compare_digest)
        S-->>C: accept
    else tags differ
        S-->>C: reject
    end

The server recomputes the tag with its secret key and accepts the message only if the tags match.

Python Sign and verify with hmac

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always compare tags with hmac.compare_digest(), never ==. A normal comparison stops at the first different character, so how long it takes can leak how many characters were right; compare_digest takes the same time either way. The key itself should come from the environment or a secrets manager, never from your source code: see the os module lesson for how to read it with os.environ.

The danger of pickle

The pickle module turns Python objects into bytes and back. Loading a pickle is not just reading data: the format can tell Python to call any function while it rebuilds the object. A pickle from an attacker can therefore run their code on your machine. Here is a harmless demonstration. The "attack" below only calls print, but it could just as easily call os.system:

Python Why unpickling untrusted data is dangerous

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The rules:

  • Never pickle.load() (or shelve, or pandas.read_pickle) data from a user, a download, a network socket or any file you do not fully control.
  • Exchange data with other systems as JSON, which can only describe numbers, strings, lists and dicts, never code.
  • If you must store Python objects for yourself, sign them with an HMAC (as above) and verify the tag before unpickling.

Also avoid eval() and exec() on user input for the same reason: they run whatever text they are given. When you need to read a Python-style literal, use ast.literal_eval(), which accepts only literals such as numbers, strings, lists and dicts.

SQL injection

SQL injection happens when user input is pasted into a SQL string, so the input can change the meaning of the query. Look at a login check that builds SQL with an f-string:

Python SQL injection and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The unsafe version turned WHERE name = 'nobody' OR '1'='1' into a condition that is always true. With a worse payload an attacker could read other tables or delete data. The fix is parameterized queries: write ? (SQLite) or %s (many other drivers) in the SQL and pass the values separately. The database driver sends the SQL and the data through different channels, so the input can never become part of the command. Details are in SQLite. Remember:

  • Parameters work for values only. You cannot parameterize a table or column name; if you need a dynamic name, check it against a fixed allow-list of known names.
  • ORMs such as SQLAlchemy parameterize for you, but the raw-SQL escape hatches (text(f"...")) are just as vulnerable as an f-string.

Command injection

The same problem appears when you build a shell command from user input. Running something like os.system(f"ping {host}") lets a user who sends example.com; rm -rf ~ run a second command. The defenses, in order of preference:

  1. Do not use a shell. Pass the command as a list of arguments; each item is delivered to the program as exactly one argument, with no shell interpretation.
  2. Avoid shell=True unless you truly need shell features, and never with untrusted text.
  3. If you must build a shell string, quote every piece with shlex.quote().
Python
import subprocess

host = input("Host to ping: ")        # imagine: "example.com; rm -rf ~"

# Dangerous: the shell reads the whole string, including the "; ..." part
subprocess.run(f"ping -c 1 {host}", shell=True)

# Safe: the list form passes the text as ONE argument and never uses a shell
subprocess.run(["ping", "-c", "1", host], check=True, timeout=10)

The editor on this page cannot start programs, but shlex is plain text processing, so you can see what quoting does:

Python shlex.quote neutralizes shell characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the naive version a shell sees the ; and runs two commands. In the quoted version the whole text, semicolon included, is one harmless argument. Also validate input where you can (a host name matches a pattern, an ID is an integer) and always pass a timeout= to subprocess.run.

A short security checklist

  • Secrets (keys, passwords, tokens) live in environment variables or a secrets manager. They never appear in source code, logs, error messages or Git history.
  • Use secrets, not random, for anything an attacker must not guess.
  • Hash passwords with a slow, salted algorithm from a vetted library; compare secrets with compare_digest.
  • Treat all external input (forms, files, network, command-line arguments) as untrusted: validate it, and never feed it to eval, pickle, SQL strings or shells.
  • Keep dependencies updated and check them with a tool such as pip-audit; most real-world breaches use known vulnerabilities in old packages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which module should you use to generate a password-reset token?

    secrets uses the operating system's secure random source. The random module is predictable and is meant for simulations and games.
  2. 2. Why is hashlib.sha256(password).hexdigest() a poor way to store passwords?

    Password storage needs a slow, salted algorithm such as PBKDF2, scrypt, bcrypt or Argon2. A plain fast hash lets attackers test billions of guesses per second.
  3. 3. Why use hmac.compare_digest(a, b) instead of a == b to check a tag?

    A normal comparison can stop at the first mismatch, and the timing may leak information. compare_digest takes constant time.
  4. 4. What is the risk of calling pickle.loads() on data from the internet?

    Pickle can instruct Python to call any function during loading, so an attacker's payload can execute commands. Use JSON for untrusted data.
  5. 5. What is the correct way to include user input in a SQL query?

    Parameterized queries keep data separate from the SQL command, so input cannot change the structure of the query.

Summary

  • Use secrets (not random) for tokens and keys; token_urlsafe(32) or token_hex(16) are good defaults.
  • hashlib creates fingerprints for integrity checks; avoid MD5 and SHA-1 for security. Store passwords with a salted, slow function (PBKDF2, scrypt, Argon2, bcrypt) and compare with hmac.compare_digest.
  • Use hmac with a secret key to sign data and detect tampering.
  • Never unpickle untrusted data, and do not use eval on input; prefer JSON and ast.literal_eval.
  • Prevent SQL injection with parameterized queries, and command injection by passing argument lists instead of using a shell (or shlex.quote as a last resort).
  • Keep secrets out of source code, validate all input and keep dependencies updated.

Next: Networking: URLs, HTTP and Sockets.