A comparison that leaks the secret slowly
A hard Java puzzle in the security mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 8. Play this one as a puzzle without the answer.
What is wrong
String.equals returns at the first differing character, so the response time reveals how many leading characters were right. With enough requests an attacker can reconstruct a valid signature one character at a time.
The fix
How to avoid it next time
Compare secrets and signatures in constant time with MessageDigest.isEqual.
Want the background? Read Hashing, Base64 and encryption in the Java concepts library.
About security mistakes
Predictable random numbers, secrets in source code, unvalidated file paths and weak hashes turn working features into vulnerabilities. They pass every functional test.
In code review: Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.
More puzzles in this family
Frequently asked questions
What is the bug in "A comparison that leaks the secret slowly"?
String.equals returns at the first differing character, so the response time reveals how many leading characters were right. With enough requests an attacker can reconstruct a valid signature one character at a time. The faulty line is line 8: return signature.equals(expected);
How do I fix it?
Replace it with: return java.security.MessageDigest.isEqual(signature.getBytes(java.nio.charset.StandardCharsets.UTF_8), expected.getBytes(java.nio.charset.StandardCharsets.UTF_8));. Compare secrets and signatures in constant time with MessageDigest.isEqual.
How do I catch security mistakes in code review?
Search for java.util.Random in security contexts, literals that look like keys, paths built from user input, and MD5 or SHA-1 used for passwords.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.