logo

Database

Kotlin Weak Random Seed

Description

Detects the use of weak or predictable seeds when initializing SecureRandom instances in Kotlin code. Using predictable seeds with SecureRandom compromises the cryptographic security of the random number generator, making it possible to guess or reproduce the generated values.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    • Look for cryptographic sinks: SecretKeySpec, IvParameterSpec, GCMParameterSpec, PBEKeySpec and PBEParameterSpec, and the init, initialize and initSign calls of KeyGenerator, KeyPairGenerator, Cipher and Signature

    • For the spec constructors, check whether the key, IV, nonce or salt argument comes from a seeded SecureRandom: filled by nextBytes (directly or in an also/apply block), or built from nextInt/nextLong/nextFloat/nextDouble through toString().toByteArray() or ByteBuffer put calls

    • For the init calls, check that the receiver is created with getInstance or declared with one of those crypto types, and that the SecureRandom passed as the last argument is seeded

    • A SecureRandom is seeded when its constructor or a setSeed call receives a number literal or a byte array converted from a plain string literal; interpolated or runtime values are not treated as predictable

    • Report the sink call; seeded generators used for non-cryptographic values such as cache keys, file names or A/B buckets are not reported

Vulnerable code example

import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec

fun buildKey(): SecretKeySpec {
    // Vulnerable: a fixed seed makes every generated key reproducible
    val rng = SecureRandom("seed".toByteArray())
    val key = ByteArray(32).also { rng.nextBytes(it) }
    return SecretKeySpec(key, "AES")...

✅ Secure code example

import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec

fun buildKey(): SecretKeySpec {
    // Safe: SecureRandom seeds itself from the system entropy source
    val rng = SecureRandom()
    val key = ByteArray(32).also { rng.nextBytes(it) }
    return SecretKeySpec(key, "AES")...