Video in progress
How do you store a verification code (OTP) sent by SMS in Redis, and how do you protect it from brute force?
I store the code as a hash, together with an attempt counter, under a key with a short TTL. I increment the counter on every wrong attempt and delete the code after the limit. I add separate limit keys for resends and for the daily SMS count.
📖 Answer
The keys:
otp:{phone} HASH code=<hmac>, attempts=0 TTL 120 s
otp:sent:{phone} STRING TTL 60 s (blocks resending)
otp:daily:{phone} STRING counter TTL 24 h
Sending:
Boolean canSend = redis.opsForValue().setIfAbsent("otp:sent:" + phone, "1", Duration.ofSeconds(60));
if (!Boolean.TRUE.equals(canSend)) throw new TooManyRequestsException();
// daily limit: INCR + EXPIRE on the first one (better in Lua)
String code = generateCode(); // SecureRandom, 6 digits
redis.opsForHash().putAll("otp:" + phone, Map.of("code", hmac(code), "attempts", "0"));
redis.expire("otp:" + phone, Duration.ofSeconds(120));
Verifying:
HINCRBY otp:{phone} attempts 1: if the result goes over 5, we delete the key and reject.- We compare against the stored hash (
MessageDigest.isEqual, a constant-time comparison). - If it's correct, we delete the key right away so the code can't be reused.
Why store the code hashed: if a Redis dump or MONITOR output ends up in someone's hands, the active codes shouldn't be visible. A 6-digit code is easy to recover from a hash, so use an HMAC with the server's secret key, not a plain SHA.
One more thing: if you limit attempts only by IP and not by phone, an attacker can switch IPs and freely work through one phone number. You need both.
Sign up to mark studied questions and save your progress.