---
title: Use CSPRNG For Security Purposes
impact: HIGH
impactDescription: prevents predictable tokens, session hijacking, and brute-force attacks
tags: random, csprng, tokens, session, cryptography, security, kotlin
---

## Use CSPRNG For Security Purposes

Standard pseudo-random number generators (PRNGs) like `java.util.Random` are predictable. If used for security purposes (sessions, tokens, passwords), an attacker can predict future values by observing previous ones. Cryptographically Secure Pseudo-Random Number Generators (CSPRNG) must be used instead.

**Incorrect (predictable random):**

```kotlin
// INSECURE - predictable!
val sessionId = Random().nextLong().toString(16)

// INSECURE - based on timestamp and weak random
val resetToken = "${System.currentTimeMillis()}-${Random().nextInt()}"

// INSECURE - Math.random()
val otp = (Math.random() * 1000000).toInt().toString()
```

**Correct (cryptographically secure):**

```kotlin
import java.security.SecureRandom
import java.util.Base64

// Cryptographically secure random source
val secureRandom = SecureRandom()

// Secure session ID or token
val bytes = ByteArray(32)
secureRandom.nextBytes(bytes)
val sessionId = Base64.getUrlEncoder().encodeToString(bytes) // 256-bit entropy

// Secure OTP generation
fun generateOTP(length: Int = 6): String {
    val secureRandom = SecureRandom()
    val stringBuilder = StringBuilder()
    repeat(length) {
        stringBuilder.append(secureRandom.nextInt(10))
    }
    return stringBuilder.toString()
}

// Secure UUID v4 (random-based)
val token = java.util.UUID.randomUUID().toString()
```

**CSPRNG in JVM/Kotlin:**

| Source | Security Level | Purpose |
|--------|----------------|---------|
| `java.security.SecureRandom` | **High (CSPRNG)** | Security tokens, salts, keys |
| `java.util.Random` | Low (PRNG) | Simulations, low-priority sorting |
| `kotlin.random.Random` | Low (PRNG) | General non-security logic |

**Tools:** SonarQube (S2245), detekt (InsecureRandom), Manual Review
