Insecure Randomness

Insecure randomness

Description

java.util.Random, Math.random(), ThreadLocalRandom and SplittableRandom are unsuitable for session IDs, tokens or temporary passwords that must resist prediction.

Potential impact

A predictable login token or temporary password may expose an account and its data. A guessed API key grants its assigned permissions, and a predictable CSRF token can weaken request protection.

Remediation

  • Use java.security.SecureRandom with its default entropy source. Avoid fixed seeds. Generate 32 bytes with SecureRandom sr = new SecureRandom(); byte[] b = new byte[32]; sr.nextBytes(b);.
  • Generate at least 128 random bits for tokens, preferably 192–256 bits, and encode them with URL-safe Base64.
  • Enforce expiry and single use for reset and email-verification tokens on the server. Limit request rates and failed attempts.

Examples

Before

java
import javax.servlet.http.*;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

public class WeakCookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        long id = ThreadLocalRandom.current().nextLong(); // Non-cryptographic PRNG
        String value = Long.toHexString(id);
        resp.addHeader("Set-Cookie", "SID=" + value + "; HttpOnly; Secure");
        resp.getWriter().println("ok");
    }
}

After

java
import javax.servlet.http.*;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;

public class StrongCookieServlet extends HttpServlet {
    private static final SecureRandom SR = new SecureRandom();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        byte[] token = new byte[32]; // 256 bits of entropy
        SR.nextBytes(token);
        String value = Base64.getUrlEncoder().withoutPadding().encodeToString(token);
        resp.addHeader("Set-Cookie", "SID=" + value + "; HttpOnly; Secure; SameSite=Strict");
        resp.getWriter().println("ok");
    }
}

The revised servlet encodes 32 bytes as unpadded URL-safe Base64 for the SID cookie. Implement server-side session validation and expiry separately.

References