← Java / Spring · Contents

JAVA-044 / Beginner

Generating tokens with java.util.Random

A02:2021 Cryptographic Failures · CWE-338 Weak PRNG

Why is this a problem?

Reset tokens can be guessed by predicting the seed.

How to fix it

java
byte[] b = new byte[32]; new SecureRandom().nextBytes(b);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(b);

Further reading