Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

A security audit found predictable random numbers used for password reset tokens and coupon codes in several services, and test randomness making some tests flaky. Set the rules and tooling for random number use across the organisation.

I would set a short rule: any value that must not be guessed, such as a token, a reset link, a coupon code, a salt or a nonce, comes from SecureRandom or a vetted library with at least 128 bits of randomness, through a small shared helper that also handles URL-safe encoding. java.util.Random and Math.random are banned in those contexts by static analysis in the build. Tests that use randomness must log their seed and allow it to be fixed, so failures can be reproduced. And because predictable tokens are already out there, we rotate and invalidate them and review where they were used.

Why this question is asked

An audit finding like this is two problems wearing one label. The first is security: tokens and coupon codes made with a predictable generator can be computed by an attacker. The second is engineering quality: random test data without a recorded seed makes failures impossible to reproduce. Interviewers ask senior candidates this to see whether they can respond to an incident, set a rule people will actually follow, and back it with tools rather than a memo. In this answer, we will recap why predictable randomness is exploitable, deal with the tokens already issued, set the rules for security-relevant values, make the right choice the easy one with a shared helper, enforce it in the build, and fix flaky tests.

1A Quick Recap: Why Predictable Randomness Is Exploitable

java.util.Random and Math.random() are pseudorandom generators with a 48-bit internal state and a public formula. If an attacker sees a couple of consecutive outputs, for example two coupon codes they received, they can reconstruct the state and compute every code the server will issue next, and often the previous ones too. If the generator was seeded with the current time, they do not even need outputs; they try the few thousand plausible seeds.

SecureRandom is a cryptographically secure generator. It is seeded from the operating system, and seeing its output gives no useful information about the next value. For anything whose value protects access or money, only that kind of generator is acceptable.

2First, Contain What Is Already Out There

Before writing rules, we deal with the exposure. Every password reset token generated with the weak generator could be predicted, so we invalidate all outstanding reset tokens, which costs users one extra email at most. Session tokens and API keys made the same way are rotated. Coupon codes are harder, because customers hold them legitimately; we keep existing codes valid only for the accounts they were issued to, add rate limiting on redemption, and issue new codes for future campaigns.

Then we review the logs: unusual numbers of reset attempts, coupon redemptions from accounts that never received them, or bursts of guesses. That tells us whether the weakness was exploited, which decides whether this is also a disclosure matter for the security and legal teams. We record what we found either way.

Step throughResponding to the audit finding
  1. Inventory weak usessearch for Random and Math.random in token code
  2. Invalidate and rotatereset tokens, sessions, keys
  3. Signs of exploitation in logs?
    YesEscalate to security and legalNoRecord the review
  4. Ship the shared helperSecureRandom, 128+ bits, URL-safe
  5. Turn on build checksban weak generators in security code
  6. Fix test seedinglog seeds, allow fixing them

6 steps in order. Play them, or step through them one at a time.

Containment comes before the new rules, because the weak values are already in customers' hands.

3The Rule for Security-Relevant Values

The rule must be short enough that everyone remembers it. Values that must not be guessed use SecureRandom, or a vetted library built on it, and carry at least 128 bits of randomness. That covers session and reset tokens, API keys, invitation and coupon codes, identifiers exposed in URLs that grant access, salts and nonces. 128 bits means 16 random bytes; an attacker making a billion guesses per second would still need far longer than the age of the universe to have a real chance.

Coupon codes deserve a note because people want them short. A short code is fine if it is not the only protection: an 8-character code from a 32-character alphabet has 40 bits, which is enough only with strict rate limiting, per-account binding and expiry. The rule says that if a value has fewer than 128 bits, its owner documents the compensating controls.

4Make the Right Choice the Easy One

Most weak tokens are written by people who needed a random string and reached for the first API they knew. So we give them something easier: a small shared helper in the platform library.

Java
public final class Tokens {
private static final SecureRandom RNG = new SecureRandom(); // thread-safe, created once
private static final Base64.Encoder URL = Base64.getUrlEncoder().withoutPadding();
public static String urlToken(int bytes) {
if (bytes < 16) throw new IllegalArgumentException("at least 128 bits");
byte[] b = new byte[bytes];
RNG.nextBytes(b);
return URL.encodeToString(b);
}
}
Tokens.urlToken(32); // 43 URL-safe characters, for example "q3Zr..." (random each call)
Tokens.urlToken(8); // IllegalArgumentException: at least 128 bits

Notice what the helper decides so callers do not have to: the generator, the instance reuse, the minimum size and the encoding. URL-safe Base64 uses minus and underscore instead of plus and slash, so tokens survive in links and query strings without escaping. A second helper for human-friendly codes can use an alphabet without confusing characters such as 0 and O. When a team needs something new, they extend the helper and everyone benefits.

5Enforce It in the Build

A rule that depends on reviewers noticing a single import will fail. So we add checks that run on every build. FindSecBugs, the security plugin for SpotBugs, reports predictable random number generators; Sonar has a similar security hotspot rule; and an ArchUnit test can forbid java.util.Random and Math.random in packages that handle authentication, tokens and payments. Check your tool versions for exact rule names. New violations fail the build, and justified exceptions, such as a Random in a load-testing tool, are suppressed with a written reason that reviewers can see.

We also add the rule to the secure coding guide with a two-line example, and to the code review checklist for authentication changes, so the tool and the people say the same thing.

6Fixing Flaky Tests That Use Randomness

Random test data is valuable because it finds cases we did not think of, but only if a failure can be repeated. The rule is that any test using randomness logs its seed and allows it to be fixed. Property-based testing libraries such as jqwik already do this, printing the seed and letting us rerun with it. For hand-written tests, the test creates a seeded generator, prints the seed on failure and reads an override from a system property.

Production code that needs randomness, for example retry jitter, should accept a RandomGenerator as a dependency instead of calling ThreadLocalRandom directly, so tests can pass a seeded one. Tests that fail only sometimes then become tests that fail every time with the printed seed, which turns a flaky test into a normal bug.

7Follow-up questions

Should we use UUID.randomUUID() for tokens?

It uses SecureRandom and has 122 random bits, so it is not predictable, and it is acceptable for many uses. But the format is long and the helper gives us 128 or more bits in a shorter, URL-safe form, with one place to change. I would allow UUIDs where they already exist and point new code at the helper.

How do you get teams to fix existing code, not just new code?

We publish the static analysis findings per service with a deadline set by severity: tokens and reset links first, within days; coupon codes next; anything else in the normal backlog. Security owns the tracking, and the platform team offers to pair on the first few fixes so the pattern spreads.

Is SecureRandom too slow for high-volume code generation?

Rarely. One shared instance produces far more tokens per second than most services issue. If profiling shows contention, a few instances fix it. Speed is never a reason to use a predictable generator for a secret.

8Conclusion

In this answer, we responded to the audit by first invalidating and rotating the weak tokens and checking for exploitation, then setting a short rule: unguessable values come from SecureRandom with at least 128 bits, through a shared helper that handles size and URL-safe encoding. We enforce the ban on Random and Math.random in security code with FindSecBugs, Sonar or ArchUnit checks in the build, and we make randomised tests reproducible by logging and allowing a fixed seed.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start with containment, because the weak values are already out there. Reset tokens made with java.util.Random can be predicted from a couple of outputs, so I would invalidate all outstanding reset tokens, rotate sessions and keys generated the same way, keep existing coupons valid only for their owners with rate limiting, and check the logs for signs of guessing so security can decide whether it is a disclosure.

Then, if they want more

Then the rule, kept short: anything that must not be guessed, such as tokens, reset links, coupon codes, salts and nonces, comes from SecureRandom or a vetted library, with at least 128 bits, and if something is shorter, like a human-friendly coupon, the owner documents the compensating controls, like rate limits and expiry.

To make that easy, the platform library gets a small Tokens helper with one shared SecureRandom, a minimum size and URL-safe Base64 encoding, so nobody reaches for Random just to get a string.

To enforce it, the build runs FindSecBugs or the Sonar rule for predictable random, plus an ArchUnit test that bans Random and Math.random in security packages, and exceptions need a written reason.

For the flaky tests, the rule is that randomised tests log their seed and allow it to be fixed, using something like jqwik or a seeded generator, and production code takes a RandomGenerator as a dependency so tests can control it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A security audit found predictable random numbers used for password reset tokens and...": https://scrivio-interview-library.netlify.app/java/types-and-values/b207d13313/