You can use org.apache.commons.lang.RandomStringUtils (http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html) to generate password using char array and java.security.SecureRandom:

public String generatePassword()
{
    return RandomStringUtils.random(DEFAULT_PASSWORD_LENGTH, 0, VALID_PW_CHARS.length(), false,
            false, VALID_PW_CHARS.toCharArray(), new SecureRandom());
}

In pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
Answer from jgr on Stack Overflow
Top answer
1 of 2
6

You can use org.apache.commons.lang.RandomStringUtils (http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html) to generate password using char array and java.security.SecureRandom:

public String generatePassword()
{
    return RandomStringUtils.random(DEFAULT_PASSWORD_LENGTH, 0, VALID_PW_CHARS.length(), false,
            false, VALID_PW_CHARS.toCharArray(), new SecureRandom());
}

In pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
2 of 2
3

Use StringBuilder instead of concatenating strings over and over. Also you should look at using string.charAt(index) instead of using substring for single chars:

import java.util.*;
import java.security.SecureRandom;

public class PassGen{

        private static final String VALID_PW_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+{}[]|:;<>?,./";
        private static final int DEFAULT_PASSWORD_LENGTH = 12;
        private static final Random RANDOM = new SecureRandom();


        // main class
        public static void main(String args[]) throws Exception {


                // Set password length
                int pwLength;
                if (args.length < 1)
                        pwLength = DEFAULT_PASSWORD_LENGTH;
                else
                        pwLength = Integer.parseInt(args[0]);

                StringBuilder pw = new StringBuilder();


                // generate password
                for (int i=0; i<pwLength; i++) {                        
                        int index = RANDOM.nextInt(VALID_PW_CHARS.length());
                        pw.append(VALID_PW_CHARS.charAt(index)));
                }

                System.out.println("pw = " + pw.toString());
        }
}

Also you are generating doubles and not restricting the index value. I did a mod of the length of the valid chars array to fix this problem.

🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.20.0 API)
public class RandomStringUtils extends Object · Generates random Strings. Use secure() to get the singleton instance based on SecureRandom() which uses a secure random number generator implementing the default random number algorithm.
🌐
Baeldung
baeldung.com › home › java › generate a secure random password in java
Generate a Secure Random Password in Java | Baeldung
January 8, 2024 - String lowerCaseLetters = RandomStringUtils. random(2, 97, 122, true, true, null, new SecureRandom());
🌐
Piotr Horzycki
peterdev.pl › secure-generation-of-random-ids-and-passwords
Secure generation of random IDs and passwords in Java | Piotr Horzycki - Java and PHP developer’s blog
January 10, 2021 - The default java.util.Random implementation is not cryptographically secure, and yet it is used by default in shorthand RandomStringUtils methods. However it is possible to pass a custom generator as the last argument, for example java.security.SecureRandom:
🌐
GitHub
github.com › apache › commons-lang › blob › master › src › main › java › org › apache › commons › lang3 › RandomStringUtils.java
commons-lang/src/main/java/org/apache/commons/lang3/RandomStringUtils.java at master · apache/commons-lang
* @see SecureRandom#getInstanceStrong() * @see ThreadLocalRandom#current() * @see RandomUtils · * @since 1.0 · */ public class RandomStringUtils { · private static final Supplier<RandomUtils> SECURE_SUPPLIER = RandomUtils::secure; · private static final RandomStringUtils INSECURE = new RandomStringUtils(RandomUtils::insecure); ·
Author   apache
🌐
Java67
java67.com › 2018 › 01 › how-to-create-random-alphabetic-or-alphanumeric-string-java.html
How to Create Random Alphabetic or AlphaNumeric String of given length in Java? SecureRandom Example | Java67
This means that it can not be used ... provides better security as compared to java.util.Random and provides a cryptographically strong random number generator....
🌐
Sonar Community
community.sonarsource.com › sonarqube cloud
java:S2245 - Identification of Commons Lang `RandomStringUtils.secure()` as safe - SonarQube Cloud - Sonar Community
September 17, 2024 - Product: sonarcloud Rule: java:S2245 We are getting a Security Hotspot for the use of Apache Commons Lang 3.17.0 RandomStringUtils.secure().randomAlphanumeric(8) (which fail our build, or failed since I now marked it as Safe). The report suggests that Sonar just does not know exactly what is the implementation of the java.util.Random which is used inside RandomStringUtils.secure().randomAlphanumeric(8) (and especially the fact that it’s based on java.security.SecureRandom when using #secure(),...
Find elsewhere
🌐
Apache Commons
commons.apache.org › proper › commons-lang › jacoco › org.apache.commons.lang3 › RandomStringUtils.java.html
RandomStringUtils.java - Apache Commons
* </p> * * @return the singleton ... 3.16.0 */ public static RandomStringUtils insecure() { return INSECURE; } /** * Creates a random string whose length is the number of characters specified....
🌐
Baeldung
baeldung.com › home › java › java string › java – generate random string
Java - Generate Random String | Baeldung
May 11, 2024 - In these Java examples, we used java.util.Random, but one point worth mentioning is that it is not cryptographically secure. Consider using java.security.SecureRandom instead for security-sensitive applications.
🌐
DeepSource
deepsource.com › directory › java › issues › JAVA-S1036
Insecure RandomUtil implementations must not be used (JAVA-S1036) ・ Java
To do so, replace the contents of the existing RandomUtil.java file with that of the one linked here. This fixed version uses an instance of java.security.SecureRandom to ensure that random numbers are securely generated.
🌐
Atlassian
docs.atlassian.com › atlassian-crowd › 1.5 › com › atlassian › crowd › integration › authentication › PasswordGenerator.html
PasswordGenerator (Atlassian Crowd 1.5 API)
TODO destroy this class and replace it with RandomStringUtils Generates a random String using a cryptographically secure random number generator.
🌐
The Mail Archive
mail-archive.com › commits@commons.apache.org › msg128390.html
(commons-lang) 02/02: Random[String]Utils.secure() now uses SecureRandom() instead of SecureRandom.getInstanceStrong()
/main/java/org/apache/commons/lang3/RandomStringUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java @@ -25,39 +25,42 @@ import java.util.function.Supplier; /** * Generates random {@link String}s. * <p> - * Starting in version 3.16.0, this class uses {@link #secure()} for static methods and adds {@link #insecure()}. + * Use {@link #secure()} to get the singleton instance based on {@link SecureRandom#SecureRandom()} which uses a secure random number generator (RNG) + * implementing the default random number algorithm..
🌐
Mkyong
mkyong.com › home › java › java – how to generate a random string
Java - How to generate a random String - Mkyong.com
May 4, 2019 - package com.mkyong; import java.security.SecureRandom; public class RandomExample { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase(); private static final String NUMBER = "0123456789"; private static final String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER; private static SecureRandom random = new SecureRandom(); public static void main(String[] args) { System.out.println("String : " + DATA_FOR_RANDOM_STRING); for (int i = 0; i < 5; i++) { System.out.println("result : " + generateRandomString(
🌐
Apache JIRA
issues.apache.org › jira › browse › LANG-1688
[LANG-1688] Why does RandomStringUtils not use SecureRandom? - ASF Jira
Now that the security problem is increasingly serious, why not use SecureRandom for Random in the RandomStringUtils.java?
🌐
GitHub
github.com › jhipster › jhipster-kotlin › issues › 183
[SECURITY] CWE-338: Vulnerability in JHipster Kotlin · Issue #183 · jhipster/jhipster-kotlin
September 13, 2019 - JHipster is using an insecure source of randomness to generate all of it's random values. JHipster relies upon apache commons lang3 RandomStringUtils.
🌐
Ruptura InfoSecurity
ruptura-infosec.com › home › hack of the month › how can random be real when random isn’t real?
How Can Random Be Real When Random Isn’t Real? | Ruptura InfoSecurity
February 10, 2025 - In our example, the java.util.Random class should be replaced with java.security.SecureRandom, which is a CSPRNG provided by the Java standard library: