×

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

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.