import java.security.SecureRandom;
import java.util.Base64;

/**
 * Generates secrets the safe way: SecureRandom, no modulo bias.
 * Run with: java TokenGenerator.java   (JDK 17 or newer)
 */
public class TokenGenerator {
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";

    /** URL-safe token carrying 'bytes' bytes of randomness (32 bytes = 256 bits = 43 characters). */
    static String token(int bytes) {
        byte[] buf = new byte[bytes];
        RANDOM.nextBytes(buf);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
    }

    /** Password from a fixed alphabet. nextInt(bound) avoids the modulo bias of (x % bound). */
    static String password(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
        }
        return sb.toString();
    }

    /** Six-digit one-time code, zero padded. */
    static String otp() {
        return String.format("%06d", RANDOM.nextInt(1_000_000));
    }

    public static void main(String[] args) {
        System.out.println("token    : " + token(32));
        System.out.println("password : " + password(16));
        System.out.println("otp      : " + otp());
    }
}
