Developer Documentation
Java
Updated September 19, 2026

Generate Secure Passwords in Java

Generate cryptographically secure random passwords without modulo bias in Java.

A password generator should draw randomness from the operating system or platform CSPRNG. Do not use predictable pseudo-random functions intended for simulations or UI effects.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Quick start#

Java
1import java.security.SecureRandom;23String alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%";4SecureRandom random = new SecureRandom();5StringBuilder out = new StringBuilder();67for (int i = ; i < ; i++) {8    out.append(alphabet.charAt(random.nextInt(alphabet.length())));9}1011System.out.println(out);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Reusable generator#

Java
1static String password(SecureRandom random, String alphabet, int length) {2    StringBuilder out = new StringBuilder(length);3    for (int i = ; i < length; i++) {4        out.append(alphabet.charAt(random.nextInt(alphabet.length())));5    }6    return out.toString();7}

Important Notes#

Reuse SecureRandom rather than constructing a predictable Random. Keep policy checks separate from the randomness primitive.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Password in other languages: