Sub topic 1
What a hash function does
A hash function takes input of any size and returns a value of fixed size. The same input always produces the same output. This chapter defines that idea precisely, shows it in code, and lists the guarantees a hash function gives you and the ones it doesn't. The rest of the tutorial builds on this definition.
Prerequisites
This chapter assumes you have:
- Basic programming skills in Python, including functions, loops, and
try/except. - Familiarity with binary and hexadecimal notation, for example that
0xFFis 255 and that one byte is 8 bits. - Working knowledge of the modulo operator (
%) and bitwise operations such as XOR, shifts, and masks. - The idea of a dictionary or map: a structure that stores values under keys.
The definition
A hash function is a function h that maps an input of arbitrary length to an output of fixed length:
h: {0,1}* -> {0,1}^nThe input is a sequence of bits of any length, including zero. The output is always exactly n bits. The output goes by several names: hash value, hash code, digest, or fingerprint. These are the same thing. "Digest" is common in cryptography, and "hash code" is common in data-structure libraries.
Three facts follow from this definition.
- The output size is fixed. SHA-256 always returns 256 bits (32 bytes), whether the input is empty or a 4 GB file.
- The function is deterministic. Given the same input,
hreturns the same output every time. If it didn't, you could not use the output to find or compare anything. - The mapping is many-to-one. The set of possible inputs is infinite, but only 2^n outputs exist. Different inputs must therefore sometimes share an output. The chapter on collisions covers this in detail.
Any function with those three traits counts as a hash function. A function can be a valid hash function and still be useless. The tutorial is mostly about the gap between "valid" and "good".
Seeing it work
Python's hashlib module exposes standard hash functions. The following program feeds inputs of very different sizes into SHA-256 and prints the input length, the digest length, and the first 16 hex characters of the digest.
import hashlib
inputs = [b"", b"a", b"hello world", b"x" * 1_000_000]
for data in inputs:
digest = hashlib.sha256(data).digest()
print(f"input {len(data):>7} bytes -> digest {len(digest)} bytes, starts {digest.hex()[:16]}")Every line reports a digest length of 32 bytes, even though the inputs range from 0 to a million bytes. Run it twice and the hex prefixes stay identical. That is determinism.
Note that hashlib works on bytes, not on str. To hash text you must first choose an encoding, for example "héllo".encode("utf-8"). Two programs that encode the same text differently will compute different hashes of what looks like the same string.
A toy hash function
The simplest function that meets the definition adds up the bytes of the input and keeps the low 8 bits:
def toy_hash(data: bytes) -> int:
return sum(data) % 256
print(toy_hash(b"hello"))
print(toy_hash(b"hello")) # same input, same output
print(toy_hash(b"ab"), toy_hash(b"ba")) # different inputs, same outputThe function is deterministic and always returns a value from 0 to 255, so it satisfies the definition. It also shows why the definition alone is weak. The inputs b"ab" and b"ba" produce the same value, because addition ignores order. A later chapter examines this weakness and how to fix it. For now, keep the lesson that a function can be a hash function without being a good one.
What a hash function does not promise
Beginners often read more into the definition than it says. These are the common misconceptions.
- A hash is not encryption. Encryption is reversible with a key. A hash function discards information, so you cannot recover the input from the output. For a 1 MB input and a 32-byte output, almost all of the information is gone.
- Different outputs prove different inputs, but equal outputs do not prove equal inputs. If
h(a) != h(b), thena != bfor certain, becausehis deterministic. Ifh(a) == h(b), the inputs might be equal or might be a collision. Code that treats equal hashes as equal data has a bug. - A hash is not unique. It is a compact label, not an identifier. The next chapters cover how likely it is that two labels clash.
- Small output does not mean low quality. A 32-bit hash is fine for picking a bucket in a hash table. It is not fine for detecting tampering. Output size is one of several properties to weigh.
Determinism has a scope
"Same input, same output" needs a qualifier: same input under the same function and the same configuration. Python's built-in hash() is the standard example. For integers it is stable. For strings, it is randomized per process as a defense against attacks you will meet in a later chapter.
import subprocess
import sys
cmd = [sys.executable, "-c", "print(hash('hello'))"]
first = subprocess.run(cmd, capture_output=True, text=True).stdout
second = subprocess.run(cmd, capture_output=True, text=True).stdout
print(first.strip(), second.strip())
print(first == second) # almost always FalseWithin one running process, hash('hello') never changes. Across two processes, the results differ unless you set the PYTHONHASHSEED environment variable. The consequence is a common mistake: using hash() to compute a value that you store on disk, send over a network, or use to assign work across several machines. Another process will compute a different value. For stored or shared hashes, use an explicitly specified function such as SHA-256 or FNV-1a, so that every program computes the same result.
Inputs must be hashable
A hash function can only be consistent if its input does not change. Python enforces this for dictionary keys: mutable containers refuse to be hashed.
try:
hash([1, 2, 3])
except TypeError as err:
print(err)
print(hash((1, 2, 3)) == hash((1, 2, 3))) # True: tuples of ints are hashableIf a list could be hashed, you could put it into a dictionary, mutate it, and then never find it again, because its hash would no longer match the bucket it was stored in. Immutable types such as int, str, bytes, and tuples of hashable items avoid the problem. The same rule applies in any language: equal objects must have equal hashes, and an object's hash must not change while it sits in a hash table.
Where hash functions are used
The definition is general, so the same idea serves very different jobs. Each job asks for different properties from the function.
| Job | What you need from the hash | Typical choice |
|---|---|---|
| Hash table lookup | Speed, even spread of outputs | A fast non-cryptographic hash such as FNV-1a |
| Hash table facing untrusted input | Speed, plus an unpredictable seed | A seeded or keyed hash |
| File integrity check | Hard to find two inputs with the same output | SHA-256 |
| Message authentication | Only holders of a secret can produce the output | HMAC |
| Password storage | Deliberately slow, salted | scrypt or a similar function |
You don't need to understand every row yet. The table shows why "hash function" names a family of tools instead of one tool. The final chapter of this tutorial returns to it as a decision guide.
Common errors at this stage
- Treating a hash as reversible, or calling it "encrypted".
- Comparing only hashes and concluding the data is equal.
- Hashing
strvalues without fixing an encoding first. - Storing the output of a per-process hash such as Python's
hash()for strings. - Using a hash whose output is too short for the job, then being surprised by clashes.
- Assuming that any deterministic fixed-size function is a good hash function.
Exercise
A teammate says: "Two files have the same SHA-256 digest, so they are guaranteed to be identical." Using only the definition from this chapter, explain why the claim is not strictly guaranteed, and say what you can conclude with certainty if the digests differ.
Show answer
A hash function maps infinitely many possible inputs onto a fixed number of outputs (2^256 for SHA-256), so distinct inputs can share an output. Equal digests therefore do not strictly prove equal inputs, although for SHA-256 such a collision is infeasible to find in practice. If the digests differ, the files are certainly different, because the function is deterministic: identical files would have produced identical digests.
Exercise
A service computes hash(user_id_string) % 4 in Python to decide which of four worker machines handles each user, with every worker running its own copy of the code. Why does this fail, and what is a safer approach?
Show answer
Python's built-in hash() for strings is randomized per process, so each worker computes a different value for the same user, and the same user is routed inconsistently. Use a function with a fixed, specified output, such as FNV-1a or a truncated SHA-256 digest of the UTF-8 encoded string, and reduce it with % 4. Then every process computes the same result.
Exercise
The toy_hash function returns sum(data) % 256. Give two different inputs that it maps to the same value, and state which part of the definition guarantees such pairs must exist for any hash function.
Show answer
b"ab" and b"ba" both give the same value, since addition ignores order. More generally, the many-to-one property guarantees pairs exist: there are infinitely many possible inputs but only a fixed number of outputs (256 here), so some inputs must share an output.