Java工具类-密码强弱判断

245 阅读1分钟

前言

密码长度大于等于8位,包含4种字符(数字、大写字母、小写字母和特殊字符)必选其三,返回true表示满足上述条件,否则返回false

代码


public class PasswordUtils {
	
	public static boolean isStrongPassword(String password) {
		return !password.equals("123456") && checkPassRule(password);
	}

	private static boolean checkPassRule(String password) {
		if (StringUtils.isBlank(password) || password.length() < 8) {
			return false;
		}
		final String ds = "0123456789";
		final String lcs = "abcdefghijklmnopqrstuvwxyz";
		final String ucs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

		String init_bits = "00000000";// 取末四位由0和1组成的字符串,依次表示是否使用了数字、小写字母、大写字母、特殊数字,0表示未使用,1表示使用,

		int bit_counter = Integer.parseInt(init_bits, 2);

		char[] input_chars = password.toCharArray();

		for (char ch : input_chars) {
			if (ds.indexOf(ch) != -1) {// 表示使用了数字
				bit_counter = bit_counter | Integer.parseInt("00001000", 2);
			} else if (lcs.indexOf(ch) != -1) {// 表示使用了小写字母
				bit_counter = bit_counter | Integer.parseInt("00000100", 2);
			} else if (ucs.indexOf(ch) != -1) {// 表示使用了大写字母
				bit_counter = bit_counter | Integer.parseInt("00000010", 2);
			} else {// 表示使用了特殊字符
				bit_counter = bit_counter | Integer.parseInt("00000001", 2);
			}
		}

		String bit_counter_Str = Integer.toBinaryString(bit_counter);

		// 取1的个数,表示使用了多少种规则
		int rule_use_count = StringUtils.countMatches(bit_counter_Str, "1");

		return rule_use_count >= 3;
	}
}