Python · security
prefer-constant-time-secret-compare
python:prefer-constant-time-secret-compare Secret-like values are compared with timing-sensitive equality operators.
- Code
- SARJ011
- Default
- error
- Fix
- none
- Languages
- python
Why
Direct equality can reveal authenticator contents through data-dependent comparison timing.
Fix
Compare secret values with `hmac.compare_digest` or `secrets.compare_digest`.
Before / after
Executed by this rule’s unit tests.
Before
Token compared with equality
def authenticated(token, expected):
return token == expected
After
Token compared in constant time
import hmac
def authenticated(token, expected):
return hmac.compare_digest(token, expected)
Limits
- Detection depends on authenticator-shaped identifier names and selected cryptographic imports.
- Tests, equality methods, literals, container membership, and existing digest comparisons are excluded.