×

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in this part, one that has at least two lowercase, two uppercase, two numerals, and two special characters.

The methods for creating a password in Java are as follows:

Method 1:

RandomPassword.java

//this program is for creating the password in java
//importing the packages required
import java.util.*;
//A class RandomPassword is created for creating the password
public class RandomPassword
{
public static void main(String[] args)
{
// The length of the required password is mentioned 
// by declaring it with the len variable
int len = 10;
System.out.println(random_Password(len));
}
    // Now, the method is for password creation
    // here, the method is used as static because we should want to create an object
static char[] random_Password(int len)
{
System.out.println("The password is creating by using the random() method : ");
System.out.print("The password generated is : ");


//To secure the password, the password must be long, and it should consist of 
//capitals, numerics, and also some other special characters
String Capital_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Small_letters = "abcdefghijklmnopqrstuvwxyz";
String number = "0123456789";
String symbol = "!@#$%^&*_=+-/.?<>)";
String value = Capital_letters + Small_letters +
number + symbol;
// the method used is random() for random passwords
Random rndmmethod = new Random();
char[] passwords = new char[len];
for (int i = 0; i < len; i++)
{
//The charAt() method was used for getting the character list
// the method nextInt() is used for reading the interger values
passwords[i] =
value.charAt(rndmmethod.nextInt(value.length()));


}
return passwords;
}
}

Output:

Java Password Generator

Method 2:

Making use of SecureRandom. using StringBuilder and nextInt() Method

Making a string of the necessary length out of a random selection of characters from the chosen ASCII range is a straightforward approach. To create a random alphabetic password, the ASCII range must include numbers, uppercase, and lowercase characters.

An easy Java application to illustrate the concept is provided below. To provide a cryptographically robust random number generator, the SecureRandom class was required instead of the Random class.

Password.java

// this program is for generating random
//import section
import java.security.SecureRandom;
public class Password
{
    //length of the password is declared
    public static String RandomPassword(int length)
    {
        // A string of required characters is declared
        final String characters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        SecureRandom rand = new SecureRandom();
        StringBuilder stringbuild = new StringBuilder();
        // for every iteration, it will select the random character
        // it will, according to the StringBuilder class
        for (int i = 0; i < length; i++)
        {
            int randomIndex = rand.nextInt(characters.length());
            stringbuild.append(characters.charAt(randomIndex));
        }
        return stringbuild.toString();
    }
    public static void main(String[] args)
    {
        int length=10;
        System.out.println(RandomPassword(length));
    }
}

Output

Java Password Generator

Method 3

 Employing Stream and SecureRandom.ints

Java 8 and later versions include the SecureRandom.ints(...) method, which may be used to effectively produce a stream of pseudorandom numbers that fall inside the given range. Using the filter(...) Stream function, you may limit the produced pseudorandom numbers to alphanumeric values. Calling the limit(...) function will force the filtering alphabetic pseudorandom numbers to stay inside the predetermined length. After that, create a String by gathering all the data in the output stream.

Random.java

//This program is for generating the random password
import java.security.SecureRandom;
public class Random
{
    // Method to generate a random alphanumeric password of a specific length
    public static String generatePassword(int length, int randomOrigin, int randomBound)
    {
        SecureRandom ranm = new SecureRandom();
        return ranm.ints(randomOrigin, randomBound + 1)
                .filter(i -> Character.isAlphabetic(i) || Character.isDigit(i))
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint,
                        StringBuilder::append)
                .toString();
    }
    public static void main(String[] args)
    {
        int length= 10;
        int randomOrigin = 48, randomBound = 122;
 
        System.out.println(generatePassword(length, randomOrigin, randomBound));
    }
}

Output

Java Password Generator

Method 4

RandomPassword.java

//Java source code demonstrating how to create a random password
//import section
import java.io.*;
import java.util.*;
public class RandomPassword
{
public static long Codes() 
{
long codes =(long)((Math.random()*9*Math.pow(10,15))+Math.pow(10,15));
return codes; // the code is then returned
}
//The method is used for declaration of the method
//The every string is then converted to the required ascii values
public static void main(String args[])
{
long codes=Codes();// the function is then called for the password
String uniquepassword="";
for (long i=codes;i!=0;i/=100)//loop is used for iterating for every two characters
{
long digits=i%100;// from the entire digits two digits are then extracted
if (digits<=90)
digits=digits+32;
// the passed two digits is then converted to ascii values
char character=(char) digits;
// adding the value (32) for the validation
uniquepassword=character+uniquepassword;//adding the character to the string
}
System.out.println("The suggested strong password is= "+uniquepassword);
}
}

Output

Java Password Generator

Related Topics

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.