SECURITY ENGINEERING · PART 4 · CRYPTOGRAPHY IN PRACTICE · HASHING · 48 OF 229

Hashing and HMAC Explained: SHA-256, MD5 and Integrity

A hash function turns any input into a short fixed fingerprint that cannot be reversed. This episode covers the properties that matter, real SHA-256 output (one changed letter flipped 131 of 256 bits), why MD5 and SHA-1 are broken, what hashes are used for, why a plain hash does not prove who sent a message, and how HMAC adds a secret key to sign webhooks and API requests.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • A one-way fingerprint
  • use SHA-256, never MD5 or SHA-1
  • a plain hash has no key
  • HMAC proves integrity and origin

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.

sha256 in Python
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.

A cryptographic hash is
  • 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.

hello vs hellp
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.

Which hash to use
  • 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.

Uses
  • 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.

Why a hash is not enough
  • 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.

hmac in Python
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.

Where you meet HMAC
  • 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.

checking an HMAC
# 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is a hash function?

A function that maps input of any size to a fixed-size output (a digest). A cryptographic hash is one-way, collision resistant and produces very different outputs for similar inputs. SHA-256 is the most widely used.

Q2Why are MD5 and SHA-1 considered insecure?

Practical collision attacks exist for both: two different inputs with the same digest can be produced, cheaply for MD5 and demonstrated for SHA-1 in 2017. This breaks their use in signatures, certificates and integrity checks against an attacker.

Q3What is the difference between hashing and encryption?

Encryption is reversible with a key and protects confidentiality. Hashing is one-way with no key and is used to verify integrity or to store verifiers such as password hashes. A hash cannot be decrypted.

Q4What is HMAC?

A hash-based message authentication code: a construction that combines a secret key with a hash function to produce a tag. Only parties holding the key can compute or verify it, so it provides both integrity and authentication of the sender.

Q5What is the difference between HMAC and a digital signature?

HMAC uses a shared secret key, so any party able to verify can also create valid tags, and it does not provide non-repudiation. A digital signature uses a private key to sign and a public key to verify, so only the key owner can produce it.

Q6How do you verify a webhook signature?

Compute the HMAC of the raw request body with the shared secret using the algorithm the provider specifies, compare it to the signature header with a constant-time comparison, and check the signed timestamp to reject replayed requests.

Q7What is a timing attack on comparison?

When a comparison stops at the first differing byte, response time reveals how many leading bytes were correct, letting an attacker recover a valid tag gradually. Constant-time comparison functions take the same time regardless of where the difference is.

Q8What is a length extension attack?

With hashes such as SHA-256, knowing hash(secret + message) lets an attacker compute a valid hash of that message with extra data appended, without knowing the secret. HMAC is designed to prevent this, which is why hand-built keyed hashes should not be used.