easy +10 pts

Constant Time Compare

Implement a timing-attack-resistant string comparison function.

In cryptography, comparing secrets (like API keys or password hashes) with a simple `==` can leak information through timing. For example, Python's `==` stops at the first mismatching byte, so an attacker can measure response times to guess the correct prefix one character at a time. Your task is to write a safer comparison function `constant_time_compare(a: str, b: str) -> bool` that: - Returns `True` if the two strings are equal, `False` otherwise. - Does not leak any information about the content of the strings via timing. - Runs in the same time regardless of where the first mismatch occurs. **Important:** Since the submission runs in a sandbox, we cannot guarantee perfect constant-time execution at the hardware level. However, your implementation must follow the standard software mitigation pattern used in libraries like `hmac.compare_digest`: it should always process the full length of the longer string and avoid early exits. We will also test that the function does not use `==` on the actual strings (by inspecting the source). **Function signature:** ```python def constant_time_compare(a: str, b: str) -> bool: ... ``` **Note:** The strings may contain only ASCII characters for simplicity.

Constraints

- Input strings are ASCII, length 0 to 10^6. - The function must not raise exceptions for any input strings. - Must run in O(max(len(a), len(b))) time and O(1) extra space.

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')
False
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compare bytes (or ord) and accumulate the XOR of differences across the entire length.
Use the length difference as part of the final result to handle different lengths.
Iterate over the longer length and treat missing characters as having code 0.
Make sure the loop always runs the full length of the longer string, never break early.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.