Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 72 ยท Authentication and Security

Password Hashing

Learn why passwords must be hashed, not encrypted, how salts work, and how to use Werkzeug's generate_password_hash and check_password_hash safely in Flask.

The moment your app has user accounts, it holds secrets that people reuse on other sites: their passwords. If your database leaks (and sooner or later, somebody's does), the damage depends on one decision you made earlier: did you store the passwords, or did you store something derived from them that cannot be turned back?

This lesson shows the standard answer. You will learn the difference between hashing and encrypting, why a plain sha256 is still the wrong tool, what a salt does, and how to use the two helpers that ship with Flask's underlying library, Werkzeug: generate_password_hash and check_password_hash. These are the building blocks for the login system in the next lesson.

Never store the password itself

There are three ways to keep a password, and only one is acceptable:

  1. Plain text. Anyone who reads the database sees every password. Never do this.
  2. Encryption. The password is scrambled with a key and can be decrypted later. If an attacker steals the database and the key (often kept on the same server), they get everything back. Your app never needs to read a password again after it is set, so there is no reason to make it recoverable.
  3. Hashing. The password goes through a one-way function. You store the result and, at login, hash what the user typed and compare. The original cannot be computed from the hash.

A hash function takes any input and returns a fixed-size fingerprint. The same input always gives the same output, and there is no practical way to go backwards. That is exactly the property you want.

Python What a hash looks like

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.

Fixed length, repeatable, and a one-letter change gives an unrelated result. So far so good, but a bare SHA-256 is still not enough for passwords.

Why a plain fast hash is not enough

Two problems remain.

Identical passwords give identical hashes. If two users choose summer2024, their stored values match, and an attacker with the database can see that. Worse, attackers keep huge precomputed lists ("rainbow tables") that map the hashes of common passwords to the passwords. Look up the hash and you have the password.

Fast hashes are fast to guess. SHA-256 is designed to be quick. A single graphics card can test billions of guesses per second, which breaks most human-chosen passwords in minutes.

The fixes are two ideas that a proper password hash combines:

  • A salt: a random string generated for each password and mixed into the hash. Two users with the same password get different stored values, and precomputed tables become useless.
  • Deliberate slowness (also called key stretching): the algorithm repeats its work many thousands of times, or uses a lot of memory, so each guess costs the attacker real time while one login for a legitimate user still takes only a fraction of a second.

The next example shows the salt problem with a naive hash and the fix with a hand-made salt, just to make the idea concrete. You will not write this yourself in a real app; Werkzeug does it for you.

Python Why salts matter

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.

Werkzeug's password helpers

Flask is built on Werkzeug, and Werkzeug includes two functions in werkzeug.security that do everything correctly:

  • generate_password_hash(password) creates a salt, hashes the password with a slow algorithm, and returns one string containing the method, the salt and the hash.
  • check_password_hash(stored, attempt) re-hashes the attempt using the salt and method found inside the stored string and compares the two in constant time.

Because the salt and method travel inside the string, you need to store only that one value, for example in a password_hash column. By default Werkzeug uses scrypt, a memory-hard algorithm. The older pbkdf2:sha256 is also supported. A default hash looks like this (shortened):

TEXT
scrypt:32768:8:1$8Vx2uPq0wB5nT1cE$3a7f0c...a long hex string...

The $ signs separate three parts: the method and its cost settings, the salt, and the hash itself.

Python generate_password_hash and check_password_hash

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 two stored strings differ because each got its own random salt, yet both verify against the same password. A wrong guess, even one capital letter off, returns False.

flowchart LR
    subgraph Register
    A["Password typed"] --> B["generate_password_hash<br/>(adds random salt, slow hash)"]
    B --> C[("Database:<br/>password_hash")]
    end
    subgraph Login
    D["Password typed"] --> E["check_password_hash<br/>(reads salt from stored value)"]
    C --> E
    E --> F{"Match?"}
    end

Registration stores only the salted hash; login hashes the attempt again with the stored salt and compares.

The browser's Python build has neither hashlib.scrypt nor hashlib.pbkdf2_hmac, so Werkzeug's hashing cannot run there as it stands. The examples below add a short, pure-Python PBKDF2 function and plug it into hashlib, so Werkzeug produces real pbkdf2:sha256 hashes. That stand-in is for these demos only: it is far slower than the C version, which is why the examples use a small iteration count. On your own machine, delete the stand-in and call generate_password_hash(password) with no method, so you get Werkzeug's default scrypt and its up-to-date cost settings. If you prefer, argon2-cffi is another solid choice.

Using the helpers in a model

Keep hashing in one place so no view can forget it. A tidy way is to hide the two functions behind methods on your user class, which never exposes the raw password:

Python A User class that hashes for you

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 same shape works unchanged with a Flask-SQLAlchemy model: add a password_hash string column and these two methods. Make the column long enough (255 characters is comfortable), because a scrypt string is around 160 characters.

Good habits around passwords

  • Give hashing a slow, modern algorithm and leave the defaults alone. Werkzeug raises its defaults as hardware improves. Do not invent your own scheme or lower the cost to speed up tests; if tests are slow, build a cheaper hash only in your test configuration.
  • Never log or print a password, not even in an error message. The same goes for the form data of a login request.
  • Do not truncate or "clean" the password. Hash exactly what the user typed. Allow long passphrases and spaces. A minimum length of eight to twelve characters is a better rule than forcing symbols.
  • Never write your own comparison with == on hashes. check_password_hash is built to compare in constant time, which closes a timing side channel.
  • Plan for upgrades. The method name is stored with each hash, so old and new algorithms can coexist. When a user logs in successfully, you can look at the prefix and, if it is out of date, re-hash the password they just typed and save the new value.
  • Use a different error for you, the same error for them. At login, say "Wrong email or password" whether the email or the password was wrong, so the form does not reveal which emails have accounts (more in the login lesson).

An upgrade-on-login check is only a few lines:

Python Re-hashing on login

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.

Hashing protects the stored copy. It does not protect against weak or reused passwords, against someone typing the password on a hacked page, or against phishing. Pair it with HTTPS, rate limiting on login attempts and, for sensitive apps, two-factor authentication. The web security lesson covers the surrounding defenses.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do we hash passwords instead of encrypting them?

    The app only needs to check a password, never to read it. A one-way hash gives exactly that, while encryption keeps the password recoverable by anyone who gets the key.
  2. 2. What is the purpose of a salt?

    A random salt per password means two users with the same password get different hashes, so lookup tables of common passwords no longer work.
  3. 3. Where does check_password_hash get the salt from?

    generate_password_hash returns one string that contains the method, salt and hash, so you store a single value.
  4. 4. Which login error message is better?

    A single generic message does not reveal whether an email address is registered.
  5. 5. Why not store hashlib.sha256(password).hexdigest()?

    Plain SHA-256 is fast and unsalted. Password hashes such as scrypt and PBKDF2 add a salt and are deliberately expensive to compute.

Summary

  • Store a one-way, salted, slow hash of each password, never the password and never something reversible.
  • generate_password_hash(password) returns one string with the method, salt and hash; check_password_hash(stored, attempt) verifies an attempt.
  • Salts make equal passwords look different and defeat precomputed tables; slowness makes mass guessing expensive.
  • Wrap the helpers in set_password and check_password methods so every part of the app hashes the same way.
  • Keep Werkzeug's default cost in production, never log passwords, and use one generic message for failed logins.
  • Re-hash on successful login when a stored hash uses an outdated method.

Next: Building a Login System, registering users and keeping them signed in with the session.