Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 15 min

Fingerprints: hashing

By the end of this chapter, you'll be able to

  • Compute the SHA-256 fingerprint of a text and of a content in Python
  • List the properties of a good hash function
  • Check the integrity of a file by comparing fingerprints
  • Tell hashing, encrypting and encoding apart

A fingerprint for data

A hash function takes data of any size (a word, a whole film) and computes a fixed-size fingerprint (a hash). Like a fingerprint: small, it still identifies the person, and you cannot rebuild the person from the fingerprint.

The most used function today is SHA-256: its fingerprint is 256 bits long, that is 64 hexadecimal characters. Python provides it in the hashlib module.

import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode()).hexdigest()

print(fingerprint("Hello"))
print(fingerprint("Hello"))            # same input → same fingerprint
print(fingerprint("hello"))            # one capital letter less
print(len(fingerprint("The whole book of savannah tales...")))
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
64

The properties of a good hash function

Nobody knows how to build two different contents with the same SHA-256 fingerprint.

Step 5 of 5
Text description of the animation
  1. On any computer, at any time.
  2. The size of the fingerprint does not depend on the size of the data.
  3. A tiny change produces a completely different fingerprint.
  4. Impossible to recover the data from the fingerprint, except by trying inputs at random.
  5. Nobody knows how to build two different contents with the same SHA-256 fingerprint.

The last property, collision resistance, is the most valuable. A collision is two different contents with the same fingerprint. Some necessarily exist (there are more possible files than fingerprints), but for SHA-256, nobody has ever managed to find one. The older functions MD5 and SHA-1 did not hold up: we know how to build collisions for them, so they must no longer be used for security.

The avalanche effect can be measured: let's count how many of the 256 bits change when we modify a single character.

import hashlib

def bits(text):
    digest = hashlib.sha256(text.encode()).digest()   # 32 bytes
    return "".join(format(byte, "08b") for byte in digest)

a, b = bits("Transfer of 5000 F CFA"), bits("Transfer of 6000 F CFA")
different = sum(x != y for x, y in zip(a, b))
print(f"{different} bits differ out of 256")
129 bits differ out of 256

On average, half of the bits change: exactly what we expect from a fingerprint that gives nothing away.

Checking a download

Back to the installer. The official site publishes the expected fingerprint. You compute the fingerprint of the file you received and compare.

import hashlib

published = hashlib.sha256(b"official content of installer v2.4").hexdigest()

def check(content, expected_fingerprint):
    return hashlib.sha256(content).hexdigest() == expected_fingerprint

from_mirror = b"official content of installer v2.4"
from_pirate = b"official content of installer v2.4 + virus"

print("mirror:", "intact" if check(from_mirror, published) else "MODIFIED")
print("pirate:", "intact" if check(from_pirate, published) else "MODIFIED")
mirror: intact
pirate: MODIFIED

Careful: this check only makes sense if the fingerprint comes from a trusted source (the official site over HTTPS). If the attacker controls the mirror and the page that displays the fingerprint, they replace both. To protect against that case, fingerprints are signed; that is what digital signatures are for, covered in a more advanced course.

Mini-lab: the avalanche effectPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: checking a list of files

A teacher shares three course files with their official fingerprints. One of the files was modified during the transfer. Write a function audit(files, official) that displays OK or ALTERED for each file.

files = {
    "lesson1.txt": b"Introduction to algorithms",
    "lesson2.txt": b"for and while loops",
    "lesson3.txt": b"Recursive functions !",
}

The official fingerprints are those of the contents b"Introduction to algorithms", b"for and while loops" and b"Recursive functions".

Hint 1
Compute the official fingerprints with hashlib.sha256(...).hexdigest() and store them in a dictionary, file name → fingerprint.
Hint 2
Loop over files.items() and compare the fingerprint of each content with official[name].
Show the solution and common mistakes
import hashlib

def sha256(content):
    return hashlib.sha256(content).hexdigest()

files = {
    "lesson1.txt": b"Introduction to algorithms",
    "lesson2.txt": b"for and while loops",
    "lesson3.txt": b"Recursive functions !",
}
official = {
    "lesson1.txt": sha256(b"Introduction to algorithms"),
    "lesson2.txt": sha256(b"for and while loops"),
    "lesson3.txt": sha256(b"Recursive functions"),
}

def audit(files, official):
    for name, content in files.items():
        state = "OK" if sha256(content) == official[name] else "ALTERED"
        print(f"{name}: {state}")

audit(files, official)
lesson1.txt: OK
lesson2.txt: OK
lesson3.txt: ALTERED

Two added characters ( !) are enough to completely change the fingerprint of the third file.

Common mistakes:

  • Hashing the file's name instead of its content: renaming a file does not change its data.
  • Comparing only the first 8 characters "to go faster": an attacker can find a fake file that shares this beginning.
  • Using MD5 because it is "shorter": it is no longer collision-resistant.

Summary

  1. 1A hash function computes a fixed-size fingerprint, always the same for the same data.
  2. 2SHA-256 has the avalanche effect, is one-way and collision-resistant; MD5 and SHA-1 are no longer safe.
  3. 3Comparing a file's fingerprint with the one published by a trusted source proves it is intact.
  4. 4Encoding is not protecting: Base64 is undone without a key; hashing and encrypting are two different things.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.