---
title: "Compare secrets in constant time · Agent Wranglers"
url: https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts/constant-time-compare
updated: 2026-10-20
licence: "All rights reserved"
---

# Compare secrets in constant time

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Recommended
- Chapter: [Access and accounts](https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts)
- Rule: Compare tokens, signatures and codes with a constant-time function, so response times reveal nothing about how close a guess was.
- How: 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.
- Check: Search the code for `==` or `===` on tokens, API keys, signatures and reset codes. Every match uses the constant-time function instead.

Example:

```python
# Bad: stops at the first wrong character
if token == stored_token: ...
# Good
if hmac.compare_digest(token, stored_token): ...
```

```ts
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)) { /* ... */ }
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers security testing playbook: https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts/constant-time-compare`.

- Previous: [Offer two-factor login](https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts/two-factor-login)
- Next: [Deny access when a check fails](https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts/fail-closed)
- [Access and accounts](https://agentwranglers.se/playbook/adversarial-testing/access-and-accounts)
