APS-13Recommended
Compare secrets in constant time
Compare tokens, signatures and codes with a constant-time function, so response times reveal nothing about how close a guess was.
How to do it
Use the comparison your platform provides, such as crypto.timingSafeEqual in Node, hmac.compare_digest in Python or hash_equals in PHP. Better still, store a hash of the token and look up the hash.
Examples
Python example
# Bad: stops at the first wrong character
if token == stored_token: ...
# Good
if hmac.compare_digest(token, stored_token): ...
TypeScript example
import { timingSafeEqual } from 'node:crypto';
// Bad
if (token === storedToken) { /* ... */ }
// Good: equal-length buffers, compared in constant time
const a = Buffer.from(token), b = Buffer.from(storedToken);
if (a.length === b.length && timingSafeEqual(a, b)) { /* ... */ }
How to check
Search the code for == or === on tokens, API keys, signatures and reset codes. Every match uses the constant-time function instead.
Sources
Related rules
- EVT-25 Sign every webhook in Integration and events
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/application-security/authentication-and-sessions/constant-time-compare">Agent Wranglers application security playbook</a>. In code you write, add a comment next to it with the same link.