Hashing, encoding and basic security · 1 / 15 Theory

Hash functions with hashlib

A hash function takes data of any size and returns a fixed-size fingerprint. It is used to detect changes, index data and compare files without reading them whole.

import hashlib

h = hashlib.sha256("hello".encode("utf-8"))
print(h.hexdigest())          # first 8: 2cf24dba...
print(len(h.hexdigest()))     # 64  (256 bits = 64 hexadecimal digits)
print(h.digest_size)          # 32  bytes

a = hashlib.sha256(b"hello mundo").hexdigest()
b = hashlib.sha256(b"hello mundo!").hexdigest()
print(a[:8], b[:8])           # one more character and the fingerprint changes completely
print(a == hashlib.sha256(b"hello mundo").hexdigest())   # True: deterministic

print(hashlib.md5(b"hello").hexdigest())   # 5d41402abc4b2a76b9719d911017c592 (not for security!)
print(sorted(hashlib.algorithms_guaranteed)[:4])

def file_fingerprint(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(65536), b""):   # in blocks, without loading everything
            h.update(block)
    return h.hexdigest()

open("demo.bin", "wb").write(b"hello mundo")
print(file_fingerprint("demo.bin") == a)    # True
  • Deterministic: the same data always gives the same fingerprint. Avalanche effect: a tiny change alters it completely.
  • One-way: it is infeasible to recover the original data from the fingerprint.
  • It is computed over bytes, not str: encode first with .encode("utf-8").
  • MD5 and SHA-1 are broken for cryptographic use (collisions can be forged): fine as a checksum, not for security. Use SHA-256 or higher.
  • For large files, feed the hash in blocks with h.update(...).

You practice it in Hash fingerprint of a text and Break a weak hash.