---
title: OTPs Must Have 20-bit Entropy Minimum
impact: MEDIUM
impactDescription: prevents attackers from guessing one-time passwords through automated trials
tags: otp, entropy, authentication, 2fa, security, kotlin
---

## OTPs Must Have 20-bit Entropy Minimum

One-Time Passwords (OTPs) are naturally shorter than session tokens, making them more susceptible to brute-force attacks. To compensate, they must have at least 20 bits of entropy (which roughly corresponds to a 6-digit numeric code) and be protected by strict rate-limiting.

**Incorrect (low entropy OTPs):**

```kotlin
// VULNERABLE: Only 4 digits = 10,000 possibilities (approx 13 bits)
val weakOtp = (1000..9999).random().toString()

// VULNERABLE: Predicatable non-random source
val timeBased = System.currentTimeMillis().toString().takeLast(6)
```

**Correct (secure, high-entropy OTP generation):**

```kotlin
import java.security.SecureRandom

private val secureRandom = SecureRandom()

// 1. 6-digit numeric OTP (~20 bits entropy) - Standard
fun generateOtp(): String {
    val number = secureRandom.nextInt(1_000_000)
    return String.format("%06d", number)
}

// 2. 8-digit numeric OTP (~26 bits entropy) - Highly Secure
fun generateStrongOtp(): String {
    val number = secureRandom.nextInt(100_000_000)
    return String.format("%08d", number)
}

// 3. Alphanumeric OTP for extra entropy in shorter lengths
// (6-char alphanumeric ≈ 30+ bits entropy)
val allowedChars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" // Avoid ambiguous chars (I/1, O/0)
fun generateAlphanumericOtp(): String {
    return (1..6).map { allowedChars[secureRandom.nextInt(allowedChars.length)] }.joinToString("")
}
```

**Security Controls for OTPs:**
1.  **Strict Rate Limiting:** This is the most important defense for OTPs. Block the user or IP after 3-5 failed attempts.
2.  **Short Expiry:** Limit the validity to a few minutes (e.g., 5 mins).
3.  **Secure Generation:** Always use a CSPRNG (`SecureRandom`).
4.  **Single Use:** Invalidate the code immediately after any attempt (success or failure) to verify it, or at least after a success.

**Tools:** OWASP ESAPI, Google Authenticator (TOTP), Manual Audit, SonarQube (S2245)
