In: Computer Science
Having a secure password is a very important practice, when much of our information is stored online. Write a program that validates a new password, following these rules:
•The password must be at least 8 characters long.
•The password must have at least one uppercase and one lowercase letter
•The password must have at least one digit.
Write a program that asks for a password, then asks again to confirm it. If the passwords don’t match or the rules are not fulfilled, prompt again. Your program should include a method that checks whether a password is valid.
In java 1.7
Console Based Password Validation Program :
package Library;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePassword {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
boolean isNotValid = true;
while(isNotValid) {
System.out.println("Enter Password : ");
String pwd =
sc.nextLine();
System.out.println("Confirm Password : ");
String cPwd =
sc.nextLine();
if(!isValidPassword(pwd)) {
isNotValid = true;
System.out.println("Your password doesn't match
the criteria of a valid paasword");
}
else
if(!confirmPassword(pwd, cPwd)) {
isNotValid = true;
System.out.println("Your password and Confirmed
password does not match.");
}else {
isNotValid = false;
break;
}
}
System.out.println("Password
created successfully.");
}
public static boolean
isValidPassword(String password)
{
// Regex to check valid password.
String regex = "^(?=.*[0-9])"//represents a digit must occur at
least once
+ "(?=.*[a-z])(?=.*[A-Z])"//) represents a lower and upper case
alphabet must occur at least once.
+ "(?=\\S+$).{8,}$"; //represents at least 8 characters
// Compile the ReGex
Pattern p = Pattern.compile(regex);
// If the password is empty
// return false
if (password == null) {
return false;
}
// Pattern class contains matcher() method
// to find matching between given password
// and regular expression.
Matcher m = p.matcher(password); //Matches the given string with
the Regex
// Return if the password
// matched the ReGex
return m.matches();
}
public static boolean confirmPassword(String pwd,
String cPwd) {
if(pwd.equals(cPwd)) return
true;
else return false;
}
}