Let us create a function which generates your password randomly. Let us see some formats of passwords.
Eg:
eR8!h0%kA*
how will it decide??
- · First, length of the password should be considered.
- · Next, uppercase, lowercase and numbers combination is needed.
- · Finally, the special characters are included.
Program implementation:
It starts
with the logic of the program.
Logic:
- · Get the length of the password from the user.
- · Call the function with password length.
- · Inside the function definition, assign uppercase, lowercase characters, numbers and special characters.
- · Combination of password is decided.
- · Using secureRandom class and stringBuilder, password is generated and displayed.
Let us implement this password generation program in java as
follows.
·
First, include the built in packages.
·
Create a public class with main() function.
·
Create object for Scanner class which reads the
system input.
·
Get the password length from user as integer.
·
Now, call the generatePwd() function with
password length.
·
Function definition assigns uppercase,lowercase,
numbers and special characters.
·
It also sets the combination of password.
·
Using secureRandom and stringBuilder classes,
the password is generated randomly.
·
Finally, the password is displayed in the output
screen.
Program:
//importing built-in packages
import java.security.SecureRandom;
import java.util.Scanner;
//Class with main() function
public class GeneratePassword {
public static void
main(String[] args) {
//Getting the
password length from the user
Scanner s1 =
new Scanner(System.in);
System.out.println("Enter
the password length");
int pwdlen =
s1.nextInt();
//Call the generatePwd() function
System.out.println("Generated Password: " +
generatePwd(pwdlen));
}
//generatePwd()
function definition
public static
String generatePwd(int length) {
//Defining
uppercase,lowercase,numbers and special characters
String uCase =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lCase =
"abcdefghijklmnopqrstuvwxyz";
String nos =
"0123456789";
String
specialChars = "!@#$%^&*()-_=+[]{};:,.<>?";
String
allChars = lCase + uCase + nos +
specialChars;
//Random
password generation
SecureRandom
random1 = new SecureRandom();
StringBuilder
pwd = new StringBuilder();
for (int i =
0; i < length; i++) {
int index
= random1.nextInt(allChars.length());
pwd.append(allChars.charAt(index));
}
return
pwd.toString();
}
}
Output:
Compile and run the program to get the output as follows..
C:\raji\blog>javac GeneratePassword.java
C:\raji\blog>java GeneratePassword
Enter the password length
9
Generated Password: Uqv]ooeQ@
This is the way of creating random password generation program in java. Hope this code is useful to you. Keep coding!!!
No comments:
Post a Comment