In Java How to Generate Strong Random Password – SecureRandom Complete Tutorial

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » In Java How to Generate Strong Random Password – SecureRandom Complete Tutorial

By default Java doesn’t have any utility which creates strong long random password. Here we have created detailed tutorial on how to generate Strong Random Password using java.security.SecureRandom API.

  • Java Security – Generate a Secure Random Password for Good
  • How to generate a secure random alphanumeric string in Java?
  • Password generator in Java source code
  • Java generate random password with special characters 🙂

We will be using ASCII Table to get Special Characters by Decimal Value in java. Take a look at below mapping between Decimal Value and Characters.

ACSII Table to Get Special Characters

Here is a flow:

  1. Create public method CrunchifyRandomPasswordGenerator() in which we will get ASCII decimal values in 3 different loops.
  2. ArrayList will be filled with ASCII decimal values
  3. crunchifyGetRandom() will get random character from above list and gets Char associated with it.
  4. We have 2 loops in main() method
    1. Outer loop to print how many passwords
    2. Inner loop to print how many characters for strong password
  5. That’s it. Just run below program and you are all set.

Java Program:

package crunchify.com.tutorial;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author crunchify.com
 * Best way to generate very secure random Password automatically
 */

public class CrunchifyRandomPasswordGenerator {

    // SecureRandom() constructs a secure random number generator (RNG) implementing the default random number algorithm.
    private final SecureRandom crunchifyRandomNo = new SecureRandom();

    private final List<Character> crunchifyValueObj;

    // Just initialize ArrayList crunchifyValueObj and add ASCII Decimal Values
    public CrunchifyRandomPasswordGenerator() {

        crunchifyValueObj = new ArrayList<>();

        // Adding ASCII Decimal value between 33 and 53
        for (int i = 33; i < 53; i++) {
            crunchifyValueObj.add((char) i);
        }

        // Adding ASCII Decimal value between 54 and 85
        for (int i = 54; i < 85; i++) {
            crunchifyValueObj.add((char) i);
        }

        // Adding ASCII Decimal value between 86 and 128
        for (int i = 86; i < 127; i++) {
            crunchifyValueObj.add((char) i);
        }
        
        // crunchifyValueObj.add((char) 64);

        // rotate() rotates the elements in the specified list by the specified distance. This will create strong password
        // Totally optional
        Collections.rotate(crunchifyValueObj, 5);
    }

    public static void main(String[] args) {

        CrunchifyRandomPasswordGenerator passwordGenerator = new CrunchifyRandomPasswordGenerator();

        log("Crunchify Password Generator Utility: \n");
        StringBuilder crunchifyBuilder = new StringBuilder();

        // Let's print total 8 passwords
        for (int loop = 1; loop <= 8; loop++) {
            // Password length should be 23 characters
            for (int length = 0; length < 42; length++) {
                crunchifyBuilder.append(passwordGenerator.crunchifyGetRandom());
            }

            log(loop, crunchifyBuilder.toString());
            crunchifyBuilder.setLength(0);
        }
    }

    // Simple log util
    private static void log(String string) {

        System.out.println(string);

    }

    // Simple log util
    private static void log(int count, String password) {

        System.out.println("Password sample " + count + ": " + password);

    }

    // Get Char value from above added Decimal values
    // Enable Logging below if you want to debug
    public char crunchifyGetRandom() {

        char crunchifyChar = this.crunchifyValueObj.get(crunchifyRandomNo.nextInt(this.crunchifyValueObj.size()));

        // log(String.valueOf(crunchifyChar));
        return crunchifyChar;
    }

}

Eclipse Console output:

Crunchify Password Generator Utility: 

Password sample 1: &fASZ\`2|;MW7^y%E@G8eObKMVP@09LEGV1Pu]a7(T
Password sample 2: 'd<&W_|_"6==>`wl`PA"0e[_/E>fYleBb\d#;O}%aN
Password sample 3: ?@/H6K@dT/~,?B0@<[yceBBS_'Jd9D`26l[XEv;WRf
Password sample 4: '"$H62TljbX6$n.PZ.N'@,68#`|!XvE_Hf/d~TSluZ
Password sample 5: Zw;acO!zlIVV@H6-cf9?hI|c{@$]C<V#Z=H@<sne9O
Password sample 6: *y9ogOM89m\3JGhZ)-`b4kl~A|Saz&4d[^~S}@/`tS
Password sample 7: $F6x~<pDBmOOk?<EaK49wNPn^EfL=:E/sX:w4To@-z
Password sample 8: eZ[`gF1,oKH:zJu+3p9"tq*kh&z$Xf)&TH1^,7h/ZQ

Process finished with exit code 0

Try to understand how you are retrieving Char from Decimal value here:

char crunchifyChar = (char) this.crunchifyValueObj.get(crunchifyRandomNo.nextInt(this.crunchifyValueObj.size()));

4 thoughts on “In Java How to Generate Strong Random Password – SecureRandom Complete Tutorial”

  1. A few observations:
    – The field ArrayListcould be List to save an unnecessary cast in crunchifyGetRandom
    – Why add the characters to the list in 3 for loops when you could do it in one loop instead?
    – Why add char 64 twice?
    – What’s the benefit in rotating the list by 5 chars if the characters are being read from it randomly?
    – The variable crunchifyBuffer should probably be named crunchifyBuilder

    Reply
    • Thanks again.

      1. Updated ArrayList to List and updated above program.
      2. Just to get different characters based on number.
      3. Fixed. Commented out line.
      4. No real benefits. Commented out line.
      5. Changed variable name.

      Keep your feedback coming on other tutorials too. Happy coding and keep visiting.

      Reply
  2. There’s nothing stopping this method from generating a random password that doesn’t meet common requirements, such as a minimum number of digits, capital letters or special characters.

    Reply
    • That’s right. Just change number from 23 to 42 and it will generate nice random password with length 42.

      Crunchify Password Generator Utility:

      Password sample 1: g.NF~)@?*+]e$8rkizIcGo(|(=1NB;@u>R}e#q:0m
      Password sample 2: BQ4'ySDrYbA)0]":Z"jKA2z-p!L3g8$@o'Ha~a.`lM
      Password sample 3: /N[7<[QR=?ZO~%e9}-}yb)W_`}`sz-AvhAN>!(QOia
      Password sample 4: va;YY"d.fP_Ft!ONk'u30n><+NiYYfS1"a,RRo?]>o
      Password sample 5: P|JSbxr&g9X:r%m-v7@TB`qOp7`|*1qi$0+e~'2P
      Password sample 6: G1crey=zQl:B8T~?cqM&VDH_Sa=?@inyk6NDvQLreR
      Password sample 7: T~Dumr1X".b6CZOW*ei{s|G@eQL@]Bf_CQn6a!9x+`
      Password sample 8: `hLX-3e=ZKi2Lytx8YG`*&q,)gZmc"S*sW9dgZ-.4D

      Process finished with exit code 0

      Reply

Leave a Comment