easy +8 pts

Constant time compare

Implement a timing-safe string comparison to prevent side-channel attacks.

In security-sensitive applications, comparing secrets (like API keys or passwords) using `==` can leak information through timing: the function returns earlier when the first differing byte is earlier. Implement `constant_time_compare(a, b)` that returns `True` if the two strings are equal and `False` otherwise, but always performs the same amount of work regardless of where (or whether) the strings differ. Your function must: - Accept two strings `a` and `b` (non-None, possibly empty). - Return a boolean. - Not leak timing information about the content or the position of differences. - Handle strings of different lengths (the length itself may be leaked, but the content comparison must be constant-time). Hint: You can use bitwise operations on the integer values of characters and accumulate a difference accumulator that is non-zero if any byte differs. Loop over the maximum length and compare characters if they exist, or simply treat missing characters as different. Ensure you always iterate the full maximum length.

Constraints

Input: two strings, each can be empty or up to 10^4 characters. Complexity: O(max(len(a), len(b))) time and O(1) additional space. The function must not use `==` on the whole strings (or slices) to decide equality.

Example

>>> constant_time_compare("abc", "abc")
True
>>> constant_time_compare("abc", "abd")
False
>>> constant_time_compare("abc", "abcd")
False
>>> constant_time_compare("", "")
True
>>> constant_time_compare("a", "b")
False
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a variable diff that accumulates the XOR of character codes; it stays 0 only if all compared characters are equal.
For differing lengths, treat the extra characters in the longer string as unequal (e.g., compare against 0).
Loop over range(max(len(a), len(b))) and use indexing with checks; always perform the same number of iterations.
Convert final diff to boolean with `return diff == 0`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.