How does a website check your password without storing it? How do download pages prove a file has not been changed? How are one-time codes made so nobody can guess them? The answers are hashing and secure randomness. Python’s built-in hashlib, hmac and secrets modules handle all three, and this lesson shows the safe way to use them.
In this lesson you will learn
- What a hash is, and its key properties
- SHA-256 with
hashlib, and hashing large files - Storing passwords safely with a salt and a slow hash
- Making tokens and codes with
secrets - Checking messages with HMAC
You should know bytes and encoding and functions.
Hashing With hashlib
import hashlib
# A hash turns any data into a short fixed-size "fingerprint"
for text in ["Dhaka", "Dhaka", "dhaka", "Dhaka is the capital of Bangladesh"]:
h = hashlib.sha256(text.encode("utf-8")).hexdigest()
print(f"{text[:20]:20} {h[:16]}... ({len(h)} hex digits)")
# Same input -> same hash; tiny change -> completely different hash.
# You cannot get the text back from the hash.
# Different algorithms, different lengths
data = b"CoreTechEd"
for name in ["md5", "sha1", "sha256", "sha512"]:
print(f"{name:7} {len(hashlib.new(name, data).hexdigest()) * 4} bits")
# Checking a file has not changed: hash it in chunks
import tempfile, os
path = os.path.join(tempfile.mkdtemp(), "notes.txt")
with open(path, "wb") as f:
f.write(b"line\n" * 100_000)
def file_sha256(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
before = file_sha256(path)
print("same after re-reading?", file_sha256(path) == before)
with open(path, "ab") as f:
f.write(b"!")
print("same after adding one byte?", file_sha256(path) == before)
Output
Dhaka 50fd531c42d3e81f... (64 hex digits)
Dhaka 50fd531c42d3e81f... (64 hex digits)
dhaka de90643718108ec9... (64 hex digits)
Dhaka is the capital 3716bf7df7d61ea3... (64 hex digits)
md5 128 bits
sha1 160 bits
sha256 256 bits
sha512 512 bits
same after re-reading? True
same after adding one byte? False
- A hash function turns data of any size into a short, fixed-size value, like a fingerprint. SHA-256 always gives 256 bits, shown as 64 hex digits.
- The same input always gives the same hash. A tiny change, even one capital letter, gives a completely different hash.
- A good hash works one way only. You cannot get the original text back from it.
- Hash functions work on bytes, so text must be encoded first.
- For big files, read in chunks and call
update()for each chunk. This hashes a file of any size without loading it all into memory. - Download sites often publish a file’s SHA-256. If your hash matches theirs, the file arrived complete and unchanged.
MD5 and SHA-1 are broken
People have found ways to make two different files with the same MD5 or SHA-1 hash. They are still fine for quick checks against accidental damage, but use SHA-256 or stronger for anything to do with security.
Passwords, Tokens and HMAC
import hashlib, hmac, secrets
# Storing passwords: use a slow, salted hash such as PBKDF2 (or scrypt)
def hash_password(password, salt=None, rounds=200_000):
salt = salt or secrets.token_bytes(16) # random salt per user
key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, rounds)
return salt, key
def check_password(password, salt, stored_key):
_, key = hash_password(password, salt)
return hmac.compare_digest(key, stored_key) # constant-time compare
salt, key = hash_password("Padma#2026")
print("salt length:", len(salt), "key length:", len(key))
print("correct password:", check_password("Padma#2026", salt, key))
print("wrong password: ", check_password("padma#2026", salt, key))
# Same password, different salt -> different stored key
salt2, key2 = hash_password("Padma#2026")
print("two users, same password, same stored key?", key == key2)
# secrets: randomness that is safe for tokens and codes
token = secrets.token_hex(16)
url_token = secrets.token_urlsafe(16)
otp = f"{secrets.randbelow(1_000_000):06d}"
print("hex token length:", len(token))
print("URL-safe token has no spaces or slashes:", " " not in url_token and "/" not in url_token)
print("OTP is 6 digits:", len(otp) == 6 and otp.isdigit())
print("random choice from a list works:", secrets.choice(["red", "green", "blue"]) in {"red", "green", "blue"})
# HMAC: prove a message came from someone who knows the secret key
secret = b"server-secret-key"
msg = b"amount=500&to=01711"
tag = hmac.new(secret, msg, hashlib.sha256).hexdigest()
print("tag valid:", hmac.compare_digest(tag, hmac.new(secret, msg, hashlib.sha256).hexdigest()))
tampered = b"amount=5000&to=01711"
print("tampered valid:", hmac.compare_digest(tag, hmac.new(secret, tampered, hashlib.sha256).hexdigest()))
Output
salt length: 16 key length: 32
correct password: True
wrong password: False
two users, same password, same stored key? False
hex token length: 32
URL-safe token has no spaces or slashes: True
OTP is 6 digits: True
random choice from a list works: True
tag valid: True
tampered valid: False
- Never store passwords as plain text. Store a hash of each password instead. To log someone in, hash what they typed and compare.
- A fast hash like plain SHA-256 is a poor choice for passwords. Attackers can try billions of guesses a second.
pbkdf2_hmacrepeats the hash 200,000 times on purpose, which makes each guess slow. - A salt is random bytes stored next to each hash. Two users with the same password get different stored keys, so one cracked password does not reveal the others.
hmac.compare_digestcompares two values in constant time, which stops attackers from learning anything by timing the check.- The
secretsmodule makes randomness that cannot be predicted. Use it for login tokens, password reset links and one-time codes (OTPs). - An HMAC is a hash mixed with a secret key. Only someone with the key can make a valid tag, so changing “500” to “5000” is caught.
| Need | Use |
|---|---|
| Check a file is unchanged | hashlib.sha256 |
| Store passwords | hashlib.pbkdf2_hmac or hashlib.scrypt, with a salt |
| Tokens, OTPs, reset links | secrets.token_urlsafe, secrets.randbelow |
| Prove a message is genuine | hmac.new(key, msg, hashlib.sha256) |
| Games, simulations, shuffling quiz questions | random |
Common Mistakes
- Using
randomfor security. Its numbers can be predicted. Usesecrets. - Storing passwords with plain SHA-256 or MD5, without a salt and without a slow hash.
- Comparing secrets with
==; usehmac.compare_digest. - Calling hashing “encryption”. Encryption can be reversed with a key; a hash cannot be reversed at all.
Practice Exercises
Exercise 1. Print the first 10 hex digits of the SHA-256 hash of "Bangladesh".
Show answer
import hashlib
h = hashlib.sha256("Bangladesh".encode("utf-8")).hexdigest()
print(h[:10])
Exercise 2. Write a function that makes a 4-digit PIN as a string, such as "0427", safe to use for security.
Show answer
import secrets
def new_pin():
return f"{secrets.randbelow(10_000):04d}"
print(len(new_pin())) # 4
randbelow(10_000) gives 0 to 9999, and :04d adds leading zeros.
Frequently Asked Questions
Should I write my own password system in a real project?
Usually no. Web frameworks such as Django already store passwords safely, and libraries such as argon2-cffi or bcrypt are built for this job. This lesson shows how they work so you understand and can check them.
Can two different inputs have the same SHA-256 hash?
In theory yes, because there are endless inputs and a fixed number of hashes. In practice nobody has ever found two such inputs for SHA-256, and finding one is far beyond today’s computers.
Summary
- A hash is a one-way, fixed-size fingerprint of some bytes.
- Use SHA-256 for file checks, and a salted slow hash such as PBKDF2 for passwords.
- Use
secrets, notrandom, for tokens and codes. - HMAC proves a message came from someone with the secret key and was not changed.
Next: Python pickle and shelve.
