Lesson 4 of 10
Hashing & Message Integrity
Cryptographic hash functions produce a fixed-length fingerprint from any input. They are one-way (cannot be reversed), deterministic, and collision-resistant. They underpin password storage, file integrity checks, digital signatures, and blockchain technology.
Properties of Cryptographic Hash Functions
- Deterministic: The same input always produces the same hash - hash('hello') always gives the same output
- Pre-image resistance: Given a hash, it is computationally infeasible to find the original input
- Second pre-image resistance: Given an input and its hash, it is infeasible to find a different input with the same hash
- Collision resistance: It is infeasible to find ANY two different inputs that produce the same hash
- Avalanche effect: Changing even one bit of input produces a completely different hash output - tiny input changes create drastic output changes
Hash Algorithms Comparison
import hashlib
import time
data = b"The quick brown fox jumps over the lazy dog"
# MD5 - BROKEN, DO NOT USE for security purposes
md5_hash = hashlib.md5(data).hexdigest()
print(f"MD5 (128-bit): {md5_hash}")
# Collisions found in 1996; two different files can have same MD5 hash
# Still used for NON-SECURITY checksums (download verification)
# SHA-1 - BROKEN, deprecated
sha1_hash = hashlib.sha1(data).hexdigest()
print(f"SHA-1 (160-bit): {sha1_hash}")
# Collision demonstrated by Google (SHAttered, 2017) - DO NOT USE
# SHA-256 - Secure, widely used
sha256_hash = hashlib.sha256(data).hexdigest()
print(f"SHA-256 (256-bit): {sha256_hash}")
# Part of SHA-2 family - cryptographically secure, used in TLS, Bitcoin, code signing
# SHA-512 - More secure, larger output
sha512_hash = hashlib.sha3_512(data).hexdigest()
print(f"SHA3-512 (512-bit): {sha512_hash}")
# SHA-3 uses different internal construction (Keccak) - immune to SHA-2 weaknesses
# File integrity verification
def verify_file(filepath, expected_hash):
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
sha256.update(chunk)
return sha256.hexdigest() == expected_hashHMAC - Authenticated Hashing
import hmac
import hashlib
import secrets
# Problem with plain hashing for authentication:
# Anyone can compute hash(message) - no secret involved
# Attacker can forge messages with valid hashes
# HMAC (Hash-based Message Authentication Code) adds a secret key
# Only someone with the secret key can produce a valid HMAC
secret_key = secrets.token_bytes(32) # 256-bit random key
message = b"Transfer $1000 to Alice"
# Create HMAC
mac = hmac.new(secret_key, message, hashlib.sha256).hexdigest()
print(f"HMAC-SHA256: {mac}")
# Verify HMAC (use hmac.compare_digest - constant-time comparison)
def verify_hmac(key, message, received_mac):
expected_mac = hmac.new(key, message, hashlib.sha256).hexdigest()
# CRITICAL: use compare_digest to prevent timing attacks
return hmac.compare_digest(expected_mac, received_mac)
# Use case: API authentication, webhook signatures
# GitHub webhooks use HMAC-SHA256 to authenticate payloads
# Django uses HMAC to sign session cookiesCommon Mistakes
- Using MD5 or SHA-1 for password hashing - they are cryptographically broken AND designed to be fast (bad for passwords). Use bcrypt/argon2 instead
- Using plain SHA-256 for password storage - SHA-256 is fast (billions per second on a GPU). Passwords need slow, work-factor algorithms. SHA-256 is appropriate only for file integrity and digital signatures
- Using == for MAC comparison (timing attack) - always use hmac.compare_digest() or equivalent constant-time comparison function
Tip
Tip
Practice Hashing Message Integrity in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Hashing Message Integrity from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Hashing Message Integrity is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- Cryptographic hash functions produce a fixed-length fingerprint from any input.
- Deterministic: The same input always produces the same hash - hash('hello') always gives the same output
- Pre-image resistance: Given a hash, it is computationally infeasible to find the original input
- Second pre-image resistance: Given an input and its hash, it is infeasible to find a different input with the same hash
Finished this lesson?