The Wayback Machine - https://web.archive.org/web/20240623235907/https://www.geeksforgeeks.org/generating-password-otp-java/
Open In App

Generating Password and OTP in Java

Last Updated : 28 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

You may go through Generate a One Time Password or Unique Identification URL article before this for better understanding. Generating Password and OTP in Java 

Many a times we forget our passwords and we opt for Forget password option and within no time we get a new password at our registered email-ID or phone no. to login our account. And every time we get a different password. Sometimes we access our bank accounts while shopping from an online store or many more ways, in order to verify our transactions from the bank account, they send us OTP(One Time Password) on our registered phone no. or our email-ID, within no time. The following code explains how to generate such Passwords and OTP within no time and what code we can use if in case we need to do so.

Method 1:

Java program explaining the generation of Password 

Java




// Java code to explain how to generate random
// password
  
// Here we are using random() method of util
// class in Java
import java.util.*;
  
public class NewClass
{
    public static void main(String[] args)
    {
        // Length of your password as I have choose
        // here to be 8
        int length = 10;
        System.out.println(geek_Password(length));
    }
  
    // This our Password generating method
    // We have use static here, so that we not to
    // make any object for it
    static char[] geek_Password(int len)
    {
        System.out.println("Generating password using random() : ");
        System.out.print("Your new password is : ");
  
        // A strong password has Cap_chars, Lower_chars,
        // numeric value and symbols. So we are using all of
        // them to generate our password
        String Capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String Small_chars = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
                String symbols = "!@#$%^&*_=+-/.?<>)";
  
  
        String values = Capital_chars + Small_chars +
                        numbers + symbols;
  
        // Using random method
        Random rndm_method = new Random();
  
        char[] password = new char[len];
  
        for (int i = 0; i < len; i++)
        {
            // Use of charAt() method : to get character value
            // Use of nextInt() as it is scanning the value as int
            password[i] =
              values.charAt(rndm_method.nextInt(values.length()));
  
        }
        return password;
    }
}


Note : The password we are generating will change every time. As we have used random() method to generate the password. 

Output : 

Generating password using random() : 
Your new password is : KHeCZBTM;-

Java program explaining the generation of OTP(One Time Password)

Java




// Java code to explain how to generate OTP
  
// Here we are using random() method of util
// class in Java
import java.util.*;
  
public class NewClass
{
    static char[] OTP(int len)
    {
        System.out.println("Generating OTP using random() : ");
        System.out.print("You OTP is : ");
  
        // Using numeric values
        String numbers = "0123456789";
  
        // Using random method
        Random rndm_method = new Random();
  
        char[] otp = new char[len];
  
        for (int i = 0; i < len; i++)
        {
            // Use of charAt() method : to get character value
            // Use of nextInt() as it is scanning the value as int
            otp[i] =
             numbers.charAt(rndm_method.nextInt(numbers.length()));
        }
        return otp;
    }
    public static void main(String[] args)
    {
        int length = 4;
        System.out.println(OTP(length));
    }
}


Note : The OTP we are generating will change every time. As we have used random() method to generate the OTP. 

Output : 

Generating OTP using random() : 
You OTP is : 5291

Method 2:

Java program explaining the generation of Password 

Java




// Java code to explain how to generate random
// password
class uniquePassword
{
public static long Code() //this code returns the  unique 16 digit code 
{  //creating a 16 digit code using Math.random function
    long code   =(long)((Math.random()*9*Math.pow(10,15))+Math.pow(10,15));
    return code; //returning the code
}
    //method to generate the password
    //by converting every two digits as an ascii value of a character
public static void main(String args[]) 
{
long code=Code();//function calling
String unique_password="";
for (long i=code;i!=0;i/=100)//a loop extracting 2 digits from the code 
    {
        long digit=i%100;//extracting two digits
        if (digit<=90)
        digit=digit+32; 
        //converting those two digits(ascii value) to its character value
        char ch=(char) digit;
        // adding 32 so that our least value be a valid character 
        unique_password=ch+unique_password;//adding the character to the string
    }
    System.out.println("unique password ="+unique_password);
    }
}
// Here we are using random() method of util
// class in Java


Note : The password we are generating will change every time. As we have used random() method to generate the password. 

Output : 

Generating password using Math.random() and ascii code: 
Your new password is : KHe%ZBT$

ascii code table:

Java program explaining the generation of OTP(One Time Password)

Java




// Java code to explain how to generate OTP
public class GenerateOTP {
//declaring a of return type String
//which on calling provides the otp
    public static String generateOTP() 
    {  //int randomPin declared to store the otp
        //since we using Math.random() hence we have to type cast it int
        //because Math.random() returns decimal value
        int randomPin   =(int) (Math.random()*9000)+1000;
        String otp  = String.valueOf(randomPin);
        return otp; //returning value of otp
    }
            public static void main(String args[])//method to call and print otp
    {
        String otpSting  =generateOTP();//function calling
        System.out.println("OTP : "+otpSting);
    }
}// Here we are using Math.random() function.
// class in Java


Note : The OTP we are generating will change every time. As we have used Math.random() function to generate the OTP. 

Output : 

Generating OTP using random() : 
You OTP is : 5291



Similar Reads

Create an OTP Generator and Validator App using React-Native
One-time passwords (OTPs) have become a popular choice for enhancing the security of various online services and applications. In this article, we'll explore how to create an OTP Generator and Validator App using React Native, a popular framework for building cross-platform mobile applications. Preview of final output: Let us have a look at how the
4 min read
Recover password of password protected zip file
In this article, we will get to know about how to get the password of a zip file. I'm using Linux I went with a quick search and came across fcrackzip. This is a free program that allows for both dictionary and brute force cracking of zip file passwords. It is not difficult to use and offers a wide range of options. Let's make a zip file then we wi
2 min read
Firebase Authentication with Phone Number OTP in Android
Many apps require their users to be authenticated. So for the purpose of authenticating the apps uses phone number authentication inside their apps. In phone authentication, the user has to verify his identity with his phone number. Inside the app user has to enter his phone number after that he will receive a verification code on his mobile number
9 min read
How to Implement OTP View in Android?
An OTP View or PinView in android is a widget that allows users to enter their PIN, OTP, etc. They are generally used for two-factor authentication or phone number verification by OTP. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-content/uploads/2023032121
2 min read
Create an OTP Verification Form in HTML CSS & JavaScript
When the application is loaded, there is a button through which the user can generate the OTP. Once the user generates the OTP, the form for verification becomes visible, the user needs to enter the correct OTP that is generated. When the user enters the OTP in the input field, and if the OTP matches then the OTP gets verified and the user can gene
4 min read
Generating random numbers in Java
Java provides three ways to generate random numbers using some built-in methods and classes as listed below: java.util.Random classMath.random method : Can Generate Random Numbers of double type.ThreadLocalRandom class1) java.util.RandomFor using this class to generate random numbers, we have to first create an instance of this class and then invok
4 min read
Keycloak - User Validation and Generating Access Tokens
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this, you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizati
2 min read
Generating random strings until a given string is generated
Given the string, the task is to generate the same string using the random combination of special character, numbers, and alphabets. Examples : Input : GFG Output :n4W mK7 k1x q;;, !g . . . . . GF, GFf GFp GFG Target matched after 167 iterations Prerequisite : Generating random Id’s in Python string.ascii_lowercase, string.digits, string.ascii_uppe
2 min read
Generating RGBA portable graphic images through C++
PNG images are capable of supporting multiple image properties such as multiple colors, degree of transparency, Gamma correction, Lossless compression, etc. PNG images are widely used and preferred for numerous types of images. For working with PNG files we will be using the PNGwriter platform-independent, wrapper open-source C++ library for libpng
3 min read
Generating API Keys For Using Any Google APIs
Like most software giants, Google provides its enthusiastic developers community with its APIs, SDKs and Services. These APIs from Google are hosted on their cloud platform, popularly known as Google Cloud Platform (GCP). Software such as Google Maps, YouTube, Gmail, etc., use the same APIs and now are available for the public for implementation at
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg