挑戰程式設計技能之檢查密碼強度
阿新 • • 發佈:2019-01-09
檢查密碼強度
1.前言
發現書中檢查密碼強度的邏輯有點不合理,根據歸納總結了一下檢驗規則:
- 少於8個字元
- 只包含數字,非常弱的密碼
- 其餘,弱密碼
- 只包含數字,非常弱的密碼
- 多於8個字元
- 包含三種類型字元(字母、數字、特殊字元),非常強密碼
- 只包含兩種字元,強密碼
- 只包含一種字元,弱密碼
- 包含三種類型字元(字母、數字、特殊字元),非常強密碼
2.java程式碼
import java.util.Scanner;public class CodeCheck {
private static String str;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print(" Please input the code:");
Scanner scanner = new Scanner(System.in);
//get the input code
if (scanner.hasNext()){
str = scanner.next();
}
scanner.close();//close the scanner
char[] code = str.toCharArray();
switch(level){
case 0:
System.out.println("the password '" + str + "' is a very weak password.");
break;
case 1:
System.out.println("the password '" + str + "' is a weak password.");
break;
case 2:
System.out.println("the password '" + str + "' is a strong password.");
break;
case 3:
System.out.println("the password '" + str + "' is a very strong password.");
break;
default:
break;
}
}
private static int checkCode(char[] code) {
// TODO Auto-generated method stub
int countNum = 0,countChar = 0,countSpecial = 0;
//to count the number of each type
for (int i = 0;i < code.length;i++){
if (code[i] >='1' && code[i] <='9'){
countNum++;
}else if (code[i] >='a' && code[i] <='z'){
countChar++;
}else if (code[i] >='A' && code[i] <='Z'){
countChar++;
}else
countSpecial++;
}
//less than 8 character
if (code.length < 8){
if (countChar == 0 && countSpecial == 0){
return 0;
}else
return 1;
}else{
//more than 8 character
if (countNum != 0 && countChar != 0 && countSpecial != 0){
return 3;
}else if (countNum == code.length || countChar == code.length || countSpecial == code.length){
return 1;
}
}
return 2;
}
}