logo

Database

Scala Secure Random Hardcoded Seed Unsafe

Description

Detects java.security.SecureRandom instances seeded with a hardcoded value through setSeed() that produce cryptographic keys, IVs, nonces or salts, or drive key generation, encryption or signing. A fixed seed makes that material reproducible.

Weakness:

034 - Insecure generation of random numbers

Category: Probabilistic Techniques

Detection Strategy

    • Code must import java.security.SecureRandom, java.security._, or java.security.*

    • Look for cryptographic sinks: new 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 is filled by nextBytes, or built from nextInt or nextLong through toString or getBytes

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

    • A SecureRandom is seeded when a setSeed call receives a number literal, an Array[Byte] of number literals or the bytes of a string literal before it is used

    • Report the sink; seeded generators used for non-cryptographic values such as cache keys or file names are not reported

Vulnerable code example

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

class VulnerableSecureRandom {
  def buildIv(): IvParameterSpec = {
    val sr = new SecureRandom()
    sr.setSeed(123456L) // VULNERABLE: a fixed seed makes every IV reproducible
    val iv = new Array[Byte](16)...

✅ Secure code example

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

class SecureRandomFixed {
  def buildIv(): IvParameterSpec = {
    val sr = new SecureRandom() // SAFE: seeds itself from the system entropy source
    val iv = new Array[Byte](16)
    sr.nextBytes(iv)...