校验规则:
密码必须由大小写字母+字符+数子组合,最少八位,不允许4位及以上连续或重复的数字或字母
PassWordUtil 工具类:
public class PassWordUtil {
/**
* 密码是否是正序或反序连续4位及以上
*
* @param pwd
* @return true为正确,false为错误。
*/
public static boolean isPasswordContinuous(String pwd) {
//正序次数
int count = 0;
//反序次数
int reverseCount = 0;
String[] strArr = pwd.split("");
//从1开始是因为划分数组时,第一个为空
for (int i = 1; i < strArr.length - 1; i++) {
if (isPositiveContinuous(strArr[i], strArr[i + 1])) {
count++;
} else {
count = 0;
}
if (isReverseContinuous(strArr[i], strArr[i + 1])) {
reverseCount++;
} else {
reverseCount = 0;
}
if (count > 2 || reverseCount > 2) break;
}
if (count > 2 || reverseCount > 2) return false;
return true;
}
/**
* 是否是正序连续
*
* @param str1
* @param str2
* @return
*/
public static boolean isPositiveContinuous(String str1, String str2) {
if (str2.hashCode() - str1.hashCode() == 1) return true;
return false;
}
/**
* 是否是反序连续
*
* @param str1
* @param str2
* @return
*/
public static boolean isReverseContinuous(String str1, String str2) {
if (str2.hashCode() - str1.hashCode() == -1) return true;
return false;
}
/**
* 验证密码是否存在多个连续重复的字符, 如!!!!, qqqq, 1111, ====, AAAA
*
* @param password 字符串
* @param repetitions 重复次数
* @return false:不重复
*/
public static boolean checkSequentialSameChars(String password, int repetitions) {
String t_password = new String(password);
int n = t_password.length();
char[] pwdCharArr = t_password.toCharArray();
boolean flag = false;
int limit_num = repetitions;
int count = 0;
for (int i = 0; i + limit_num <= n; i++) {
count = 0;
for (int j = 0; j < limit_num - 1; j++) {
if (pwdCharArr[i + j] == pwdCharArr[i + j + 1]) {
count++;
if (count == limit_num - 1) {
return true;
}
}
}
}
return flag;
}
/**
* - 字母区分大小写,可输入符号<br/>
* - 密码必须同时包含大写字母、小写字母、特殊符号和数字<br/>
* - 密码长度8-20位<br/>
* - 密码中不能存在连续4个及以上的数字或字母(如:1234、7654、abcd、defgh等)<br/>
* - 验证密码是否存在4个及以上连续重复的字符, 如!!!!, qqqq, 1111, ====, AAAA <br/>
* @param password 密码
* @return true为正确,false为错误
*/
public static boolean isPasswordAvailable(String password) {
//必须同时包含字母数字并且是8-20位,字符需要哪些可以调整正则,不可能无限支持所有的字符,一般都是指定部分字符
String str = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,20}";
if (password.matches(str) && !checkSequentialSameChars(password, 4)) {
return isPasswordContinuous(password);
}
return false;
}
public static void main(String[] args) {
System.out.println(isPasswordAvailable("11111111") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("Aa@12345678") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("abABCd@7415") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("aaaaABbbbb1@") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("AAacd123456@") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("1Q2@222e4r") ? "符合规范" : "不符合");
System.out.println(isPasswordAvailable("12121212.Aa111") ? "符合规范" : "不符合");
}
}
参考:
常见密码正则表达式:
https://www.cnblogs.com/daizhongxing/p/11593137.html
https://blog.youkuaiyun.com/mzz5240/article/details/46940983