Hardware Security
What weakness lurks in the password comparison function above, and what is the fix?
int check(const char *in, const char *pw, int n) {
for (int i = 0; i < n; i++)
if (in[i] != pw[i]) return 0;
return 1;
}
- ALarge n makes the result wrong; shrink n before comparing
- BIt stops at the first mismatch, so processing time reveals how many leading characters match; compare to the end and return the combined result
- CThere is no problem; it is safe as is
Show answer and explanation
Answer: B. It stops at the first mismatch, so processing time reveals how many leading characters match; compare to the end and return the combined result
The function returns immediately if the first character differs and only after checking the second if the first matches, so time grows with the number of matching characters. An attacker trying candidates one character at a time and keeping the slower ones can guess the password without trying every combination. Accumulating the differences of all characters, for example with XOR, and deciding at the end makes the time independent of how many characters match.
- A. The result is correct, but time leaks information.
- B. Correct. The key is not to create timing differences.
- C. It is vulnerable to timing attacks.