Notes
A hash function
A hash function takes any input and returns a fixed-size value called a digest. Here is SHA two fifty six of the word hello: sixty four hex characters, which is thirty two bytes. A five gigabyte file also gives thirty two bytes. The same input always gives the same output, on any machine, and there is no key and nothing secret. That makes a hash a fingerprint: a short value that stands for the whole content.
import hashlib hashlib.sha256(b"hello").hexdigest() # 2cf24dba5fb0a30e26e83b2ac5b9e29e # 1b161e5c1fa7425e73043362938b9824 # 5 bytes in: 32 bytes out # 5 GB in: 32 bytes out # same input: same output, always # no key, nothing secret
Three properties
Three properties make a hash cryptographic. It is one-way: from the digest you cannot work back to the input. It is collision resistant: nobody can find two different inputs with the same digest. And it is unpredictable: a tiny change to the input gives a completely different digest. If any one of these fails, the hash is broken for security use, even if it still works as a simple checksum.
- 1. One-way: you cannot work back from digest to input
- 2. Collision resistant: you cannot find two inputs with the same digest
- 3. Unpredictable: a tiny change gives a completely different digest
- lose any one and the hash is broken
The avalanche effect
Here is that third property measured. We hashed hello and then hellp, one letter different. The two digests have nothing in common. Counting bit by bit, one hundred and thirty one of the two hundred and fifty six bits changed, which is about half, exactly what a good hash should do. This is called the avalanche effect, and it means a digest tells an attacker nothing about inputs that are similar to the real one.
sha256(b"hello") # 2cf24dba5fb0a30e... sha256(b"hellp") # fdd7585e08c4e2af... # bits that differ: 131 of 256 # about half, as it should be # so a digest tells you nothing # about a "nearby" input
Broken hashes
Not every hash is safe. MD five is broken: two different files with the same MD five can be produced in seconds on a laptop. SHA one fell in twenty seventeen, when researchers published two different PDF files with the same digest. Attackers have used such collisions to forge certificates. Neither may be used for signatures, certificates or integrity against an attacker. Use the SHA two family, such as SHA two fifty six, or SHA three or BLAKE.
- MD5 (128-bit): collisions in seconds on a laptop
- SHA-1 (160-bit): a real collision published in 2017
- both: never for signatures, certificates or integrity
- use: SHA-256, SHA-384, SHA-512 (the SHA-2 family)
- also good: SHA-3, BLAKE2, BLAKE3
Where hashes are used
You meet hashes everywhere. A download page publishes the SHA two fifty six so you can check the file arrived intact. Git names every commit and file by its hash, which is why history cannot be changed quietly. Container images are pinned by digest. Digital signatures sign the hash of a file instead of the whole file. Security teams share hashes of malware as indicators. And passwords are stored as hashes, with special rules that get their own episode.
- file integrity: compare the published SHA-256
- git: every commit and file is named by its hash
- container images: pulled by digest (sha256:...)
- digital signatures: sign the hash, not the whole file
- malware: hashes as indicators
- passwords: next episode
The gap
A plain hash has a gap. Anyone can compute it. If an attacker can change a message in transit, they also replace the hash with a fresh one, and the check passes. In the same way, a checksum published on the same server as the download is useless if that server is compromised: the attacker updates both. To prove that a message came from someone specific, the check needs a secret that the attacker does not have.
- anyone can compute a hash
- an attacker who changes the message simply computes a new hash to go with it
- a hash beside a download on the same hacked server protects nothing
- you need a secret the attacker does not have
HMAC
That is HMAC: a hash-based message authentication code. It mixes a secret key into the hash in a carefully designed way. Here we computed the HMAC of a payment message with a secret key. When we changed the amount from one hundred to nine hundred, the result changed completely, and without the key an attacker cannot produce the correct new value. The receiver, who has the same key, recomputes it and compares. A match proves integrity and origin.
import hmac, hashlib
hmac.new(b"secret-key",
b"amount=100&to=alice",
hashlib.sha256).hexdigest()
# f7c2b4c23af4c2f85be636d5e531da17
# fa2390624c849f7cfa6ab723fb39a30a
# change 100 to 900:
# d5cac77d502c4c5d... HMAC in practice
HMAC is everywhere in practice. When GitHub, Stripe or Slack send a webhook to your server, they include an HMAC of the body in a header, and you must verify it, or anyone on the internet can send you fake events. AWS signs every API request with HMAC. A JWT with the HS two fifty six algorithm is signed with HMAC. Web frameworks use it to sign cookies. Checking these signatures is a routine and important code review item.
- webhooks: GitHub, Stripe and Slack sign each request; you verify the header
- API request signing: AWS Signature Version 4
- JWTs signed with HS256
- signed cookies and session tokens
- TLS and SSH record integrity in older cipher suites
Verify correctly
Three details matter when verifying. Compare with a constant-time function such as compare digest. A normal equals stops at the first wrong byte, and the tiny timing difference lets an attacker guess the value byte by byte. Include a timestamp in what is signed and reject old requests, or an attacker can replay a valid message. And verify the raw bytes you received, before any parsing changes them.
# constant-time comparison hmac.compare_digest(expected, got) # not: expected == got # == stops at the first wrong # byte; timing leaks the answer # sign a timestamp too, and # reject old requests (replay) # verify the raw body bytes
Common mistakes
Mistakes. MD five or SHA one used for security. A plain hash where a keyed MAC or a signature is needed. Building your own keyed hash by joining the key and the message, which with SHA two allows a length extension attack; use HMAC. Comparing with a normal equals. No replay protection. Webhook signatures that are never verified. And calling a hash encryption, when nothing is ever decrypted.
- MD5 or SHA-1 for security
- a plain hash where a MAC or signature is needed
- hash(key + message) built by hand instead of HMAC
- comparing with ==
- no replay protection
- webhook signatures never verified
- a hash called "encryption"
Say it like this
In the interview: a hash is a one-way fingerprint that shows data has not changed, but anyone can compute it. An HMAC adds a shared secret key, so it proves integrity and origin between two parties who both hold the key. A digital signature uses a private key, so anyone can verify it with the public key and only one party could have made it. I use SHA two fifty six, HMAC for webhooks and API signing, and constant-time comparison.
- "A hash proves data has not changed, but anyone can
- compute it. An HMAC adds a shared secret, proving
- integrity and origin between two parties. A signature uses
- a private key, so anyone can
- verify and only one can
- sign."