In the following example, a password is checked for its strength. If the password contains less than 6 characters, it is invalid. If the password contains less than 10 characters it gets the password strength medium, if it contains more than 10 characters it is strong.
Furthermore, the password must contain at least one lowercase letter, one uppercase letter, one number and one special character. The output of this program is the strength of the password, or an indication of a missing character.
The code is a Java program that checks the strength of a password entered by the user. The program uses the following steps to check the strength of the password:
The program uses the Scanner class to read the password entered by the user and the Character class to check the type of characters in the password.
import java.util.Scanner;
class PasswordCheck{
public static void checkPassword(String password) {
int upperChars = 0, lowerChars = 0, specialChars = 0, digits = 0, length;
char ch;
length = password.length();
if (length < 6) {
System.out.println("Password must be at least 6 characters long!\n");
return;
} else {
for (int i = 0; i < length; i++) {
ch = password.charAt(i);
if (Character.isUpperCase(ch)) {
upperChars++;
} else if (Character.isLowerCase(ch)) {
lowerChars++;
} else if (Character.isDigit(ch)) {
digits++;
} else {
specialChars++;
}
}
}
if (upperChars != 0 && lowerChars != 0 && digits != 0 && specialChars != 0) {
if (length >= 10) {
System.out.println("The strength of password is strong.\n");
} else {
System.out.println("The strength of password is medium.\n");
}
} else {
if (upperChars == 0)
System.out.println("Password must contain at least one uppercase character!\n");
if (lowerChars == 0)
System.out.println("Password must contain at least one lowercase character!\n");
if (specialChars == 0)
System.out.println("Password must contain at least one special character!\n");
if (digits == 0)
System.out.println("Password must contain at least one digit!\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter password: ");
String password = scan.nextLine();
scan.close();
checkPassword(password);
}
}
[first_run]
Please enter password: 34rT%
Password must be at least 6 characters long!
[second_run]
Please enter password: 23456weretsDFDS
Password must contain at least one special character!
[third_run]
Please enter password: 456ztr7TZ$$
The strength of password is strong.