Implement cryptographically secure 6-digit OTP generation, 3-attempt invalidation, and IP/MSISDN sliding window backoff to stop brute-force attacks.
One-Time Passcodes (OTP) remain the most ubiquitous authentication factor across global consumer applications. However, poorly configured token lifecycles expose systems to brute-force enumerations and SMS toll fraud. This article details a hardened OTP architecture balancing conversion ergonomics with cryptographic defense.
1 Cryptographic Token Generation and Entropy
Never use pseudorandom functions such as Math.random() or standard rand() to generate passcodes. Always use cryptographically secure pseudo-random number generators (CSPRNG):
Python: secrets.randbelow(1_000_000) padded to 6 digits.
Node.js: crypto.randomInt(100000, 1000000).
A 6-digit decimal code provides 1,000,000 possibilities (19.93 bits of entropy). Without rate limiting, a distributed botnet testing 100 requests per second will guess the token in under 83 minutes.
2 Three-Strike Token Invalidation
Strictly limit each issued passcode to a maximum of 3 incorrect validation attempts. On the third failure:
1. Immediately invalidate the token in cache (Redis/KV).
2. Record a security telemetry metric (suspicious_otp_failures).
3. Require the client to initiate a brand-new generation lifecycle subject to exponential backoff.
3 Sliding Window Rate Limiting and Backoff Algorithm
Enforce rate limiting across two orthogonal keys: destination phone number (MSISDN) and client IP address. Recommended backoff schedule:
- Attempt 1: Immediate dispatch.
- Attempt 2: 30-second delay minimum.
- Attempt 3: 60-second delay.
- Attempt 4: 300-second (5-minute) cooldown.
- 5+ Attempts in 1 Hour: Hard lock for 60 minutes with fraud alert notification.
Frequently Asked Questions • OTP & 2FA Engineering
Numeric 6-digit codes are standard because mobile operating systems (iOS and Android) automatically parse numeric codes from incoming SMS and offer 1-tap keyboard auto-fill.
Between 3 and 5 minutes (180 to 300 seconds). Shorter windows trigger user frustration during carrier delays; longer windows increase replay risk.