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

## Use CSPRNG For Security Purposes

Non-cryptographic random generators are predictable. Attackers can guess session tokens, OTPs, and password reset links generated with weak random sources.

**Incorrect (predictable random):**

```go
import "math/rand"

// INSECURE - predictable!
sessionId := fmt.Sprintf("%d", rand.Intn(1000000))

// INSECURE - Seeded with time isn't enough for security tokens
rand.Seed(time.Now().UnixNano())
token := rand.Int63()
```

**Correct (cryptographically secure):**

```go
import (
    "crypto/rand"
    "encoding/hex"
    "math/big"
)

// Cryptographically secure session ID
b := make([]byte, 32)
rand.Read(b)
sessionId := hex.EncodeToString(b) // 256-bit entropy

// Secure OTP generation
func generateOTP(length int) string {
    max := big.NewInt(int64(math.Pow10(length)))
    n, _ := rand.Int(rand.Reader, max)
    return fmt.Sprintf("%0*d", length, n)
}
```

**CSPRNG by language:**

| Language | Secure | Insecure |
|----------|--------|----------|
| Go | `crypto/rand` | `math/rand` |

**Tools:** SonarQube, Semgrep, `crypto/rand`
