Courses

Magic Hashes
OSWE · Chapter 15

Magic Hashes

"Magic hashes" are a specific PHP loose-comparison bug (covered conceptually in the Type Juggling chapter) where certain hash strings that begin with "0e" followed by only digits are interpreted as scientific-notation zero, letting two completely different hash values compare as equal.

Key concepts

  • Any hash function whose output can coincidentally start with `0e` followed by digits only is vulnerable if compared with `==` rather than `===`.
  • This mainly matters for password/token verification code, where an attacker who can influence one side of the comparison (e.g. supply a "magic" input) can forge a match without knowing the real secret.
  • MD5 and SHA-1 have both been used historically in magic-hash proof-of-concepts because their hex output occasionally happens to start with "0e".
  • The fix from the previous chapter applies directly: always use `===` (or a constant-time comparison function) for any security-sensitive string comparison.

Example

<?php
// Two different inputs whose MD5 both happen to look like "0e..." numbers
var_dump(md5("240610708") == md5("QNKCDZO")); // true in loose comparison

Try it yourself

Look up two known "magic hash" MD5 collision strings and verify with `var_dump(... == ...)` in a local PHP sandbox that they compare equal under loose comparison but not under `===`.

@ Daniel Burlacu