密码校验工具类

该代码实现了一个用于评估密码安全性的工具类`PasswordCheckUtil`。它检查密码的长度、是否包含数字、字母、大小写字母、特殊字符,以及是否存在键盘横向、斜向和逻辑上的连续字符。同时,还检测了密码是否包含常用词。配置项通过`PasswordCheckConfig`类进行控制,允许开启或关闭各种检查。
摘要由CSDN通过智能技术生成
package com.zpeng.password;

import java.util.Arrays;
import java.util.List;

public class PasswordCheckUtil {

    /**
     * @return 符合要求 返回true
     * @brief 评估密码中包含的字符类型是否符合要求
     * @param[in] password            密码字符串
     */
    public static boolean evalPassword(String password) {
        if (password == null || "".equals(password)) {
            return false;
        }
        boolean flag = false;

        /**
         * 检测长度
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_PASSWORD_LENGTH)) {
            flag = checkPasswordLength(password);
            if (!flag) {
                return false;
            }
        }

        /**
         * 检测包含数字
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_CONTAIN_DIGIT)) {
            flag = checkContainDigit(password);
            if (!flag) {
                return false;
            }
        }

        /**
         *  检测包含字母
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_CONTAIN_CASE)) {
            flag = checkContainCase(password);
            if (!flag) {
                return false;
            }
        }

        /**
         * 检测字母区分大小写
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_DISTINGGUISH_CASE)) {
            //检测包含小写字母
            if ("enable".equals(PasswordCheckConfig.CHECK_LOWER_CASE)) {
                flag = checkContainLowerCase(password);
                if (!flag) {
                    return false;
                }
            }

            //检测包含大写字母
            if ("enable".equals(PasswordCheckConfig.CHECK_UPPER_CASE)) {
                flag = checkContainUpperCase(password);
                if (!flag) {
                    return false;
                }
            }
        }

        /**
         * 检测包含特殊符号
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_CONTAIN_SPECIAL_CHAR)) {
            flag = checkContainSpecialChar(password);
            if (!flag) {
                return false;
            }
        }

        /**
         * 检测键盘横向连续
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_HORIZONTAL_KEY_SEQUENTIAL)) {
            flag = checkLateralKeyboardSite(password);
            if (flag) {
                return false;
            }
        }

        /**
         * 检测键盘斜向连续
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_SLOPE_KEY_SEQUENTIAL)) {
            flag = checkKeyboardSlantSite(password);
            if (flag) {
                return false;
            }
        }

        /**
         * 检测逻辑位置连续
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_LOGIC_SEQUENTIAL)) {
            flag = checkSequentialChars(password);
            if (flag) {
                return false;
            }
        }

        /**
         * 检测相邻字符是否相同
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_SEQUENTIAL_CHAR_SAME)) {
            flag = checkSequentialSameChars(password);
            if (flag) {
                return false;
            }
        }

        /**
         *  检测常用词库
         */
        if ("enable".equals(PasswordCheckConfig.CHECK_SIMPLE_WORD)) {
            flag = checkSimpleWord(password);
            if (flag) {
                return false;
            }
        }

        return true;
    }

    /**
     * @return 符合长度要求 返回true
     * @brief 检测密码中字符长度
     * @param[in] password            密码字符串
     */
    public static boolean checkPasswordLength(String password) {
        boolean flag = false;

        if ("".equals(PasswordCheckConfig.MAX_LENGTH)) {
            if (password.length() >= Integer.parseInt(PasswordCheckConfig.MIN_LENGTH)) {
                flag = true;
            }
        } else {
            if (password.length() >= Integer.parseInt(PasswordCheckConfig.MIN_LENGTH) && password.length() <= Integer
                .parseInt(PasswordCheckConfig.MAX_LENGTH)) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * @return 包含数字 返回true
     * @brief 检测密码中是否包含数字
     * @param[in] password            密码字符串
     */
    public static boolean checkContainDigit(String password) {
        char[] chPass = password.toCharArray();
        boolean flag = false;
        int num_count = 0;

        for (int i = 0; i < chPass.length; i++) {
            if (Character.isDigit(chPass[i])) {
                num_count++;
            }
        }

        if (num_count >= 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 包含字母 返回true
     * @brief 检测密码中是否包含字母(不区分大小写)
     * @param[in] password            密码字符串
     */
    public static boolean checkContainCase(String password) {
        char[] chPass = password.toCharArray();
        boolean flag = false;
        int char_count = 0;

        for (int i = 0; i < chPass.length; i++) {
            if (Character.isLetter(chPass[i])) {
                char_count++;
            }
        }

        if (char_count >= 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 包含小写字母 返回true
     * @brief 检测密码中是否包含小写字母
     * @param[in] password            密码字符串
     */
    public static boolean checkContainLowerCase(String password) {
        char[] chPass = password.toCharArray();
        boolean flag = false;
        int char_count = 0;

        for (int i = 0; i < chPass.length; i++) {
            if (Character.isLowerCase(chPass[i])) {
                char_count++;
            }
        }

        if (char_count >= 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 包含大写字母 返回true
     * @brief 检测密码中是否包含大写字母
     * @param[in] password            密码字符串
     */
    public static boolean checkContainUpperCase(String password) {
        char[] chPass = password.toCharArray();
        boolean flag = false;
        int char_count = 0;

        for (int i = 0; i < chPass.length; i++) {
            if (Character.isUpperCase(chPass[i])) {
                char_count++;
            }
        }

        if (char_count >= 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 包含特殊符号 返回true
     * @brief 检测密码中是否包含特殊符号
     * @param[in] password            密码字符串
     */
    public static boolean checkContainSpecialChar(String password) {
        char[] chPass = password.toCharArray();
        boolean flag = false;
        int special_count = 0;

        for (int i = 0; i < chPass.length; i++) {
            if (PasswordCheckConfig.SPECIAL_CHAR.indexOf(chPass[i]) != -1) {
                special_count++;
            }
        }

        if (special_count >= 1) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 含有横向连续字符串 返回true
     * @brief 键盘规则匹配器 横向连续检测
     * @param[in] password            密码字符串
     */
    public static boolean checkLateralKeyboardSite(String password) {
        String t_password = new String(password);
        //将所有输入字符转为小写
        t_password = t_password.toLowerCase();
        int n = t_password.length();
        /**
         * 键盘横向规则检测
         */
        boolean flag = false;
        int arrLen = PasswordCheckConfig.KEYBOARD_HORIZONTAL_ARR.length;
        int limit_num = Integer.parseInt(PasswordCheckConfig.LIMIT_HORIZONTAL_NUM_KEY);

        for (int i = 0; i + limit_num <= n; i++) {
            String str = t_password.substring(i, i + limit_num);
            String distinguishStr = password.substring(i, i + limit_num);

            for (int j = 0; j < arrLen; j++) {
                String configStr = PasswordCheckConfig.KEYBOARD_HORIZONTAL_ARR[j];
                String revOrderStr = new StringBuffer(PasswordCheckConfig.KEYBOARD_HORIZONTAL_ARR[j]).reverse().toString();

                //检测包含字母(区分大小写)
                if ("enable".equals(PasswordCheckConfig.CHECK_DISTINGGUISH_CASE)) {
                    //考虑 大写键盘匹配的情况
                    String UpperStr = PasswordCheckConfig.KEYBOARD_HORIZONTAL_ARR[j].toUpperCase();
                    if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) {
                        flag = true;
                        return flag;
                    }
                    //考虑逆序输入情况下 连续输入
                    String revUpperStr = new StringBuffer(UpperStr).reverse().toString();
                    if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) {
                        flag = true;
                        return flag;
                    }
                } else {
                    if (configStr.indexOf(str) != -1) {
                        flag = true;
                        return flag;
                    }
                    //考虑逆序输入情况下 连续输入
                    if (revOrderStr.indexOf(str) != -1) {
                        flag = true;
                        return flag;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * @return 含有斜向连续字符串 返回true
     * @brief 键盘规则匹配器 斜向规则检测
     * @param[in] password            密码字符串
     */
    public static boolean checkKeyboardSlantSite(String password) {
        String t_password = new String(password);
        t_password = t_password.toLowerCase();
        int n = t_password.length();
        /**
         * 键盘斜线方向规则检测
         */
        boolean flag = false;
        int arrLen = PasswordCheckConfig.KEYBOARD_SLOPE_ARR.length;
        int limit_num = Integer.parseInt(PasswordCheckConfig.LIMIT_SLOPE_NUM_KEY);

        for (int i = 0; i + limit_num <= n; i++) {
            String str = t_password.substring(i, i + limit_num);
            String distinguishStr = password.substring(i, i + limit_num);
            for (int j = 0; j < arrLen; j++) {
                String configStr = PasswordCheckConfig.KEYBOARD_SLOPE_ARR[j];
                String revOrderStr = new StringBuffer(PasswordCheckConfig.KEYBOARD_SLOPE_ARR[j]).reverse().toString();
                //检测包含字母(区分大小写)
                if ("enable".equals(PasswordCheckConfig.CHECK_DISTINGGUISH_CASE)) {

                    //考虑 大写键盘匹配的情况
                    String UpperStr = PasswordCheckConfig.KEYBOARD_SLOPE_ARR[j].toUpperCase();
                    if ((configStr.indexOf(distinguishStr) != -1) || (UpperStr.indexOf(distinguishStr) != -1)) {
                        flag = true;
                        return flag;
                    }
                    //考虑逆序输入情况下 连续输入
                    String revUpperStr = new StringBuffer(UpperStr).reverse().toString();
                    if ((revOrderStr.indexOf(distinguishStr) != -1) || (revUpperStr.indexOf(distinguishStr) != -1)) {
                        flag = true;
                        return flag;
                    }
                } else {
                    if (configStr.indexOf(str) != -1) {
                        flag = true;
                        return flag;
                    }
                    //考虑逆序输入情况下 连续输入
                    if (revOrderStr.indexOf(str) != -1) {
                        flag = true;
                        return flag;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * @return 含有a-z,z-a连续字符串 返回true
     * @brief 评估a-z,z-a这样的连续字符
     * @param[in] password            密码字符串
     */
    public static boolean checkSequentialChars(String password) {
        String t_password = new String(password);
        boolean flag = false;
        int limit_num = Integer.parseInt(PasswordCheckConfig.LIMIT_LOGIC_NUM_CHAR);
        int normal_count = 0;
        int reversed_count = 0;

        //检测包含字母(区分大小写)
        if ("enable".equals(PasswordCheckConfig.CHECK_DISTINGGUISH_CASE)) {

        } else {
            t_password = t_password.toLowerCase();
        }
        int n = t_password.length();
        char[] pwdCharArr = t_password.toCharArray();

        for (int i = 0; i + limit_num <= n; i++) {
            normal_count = 0;
            reversed_count = 0;
            for (int j = 0; j < limit_num - 1; j++) {
                if (pwdCharArr[i + j + 1] - pwdCharArr[i + j] == 1) {
                    normal_count++;
                    if (normal_count == limit_num - 1) {
                        return true;
                    }
                }

                if (pwdCharArr[i + j] - pwdCharArr[i + j + 1] == 1) {
                    reversed_count++;
                    if (reversed_count == limit_num - 1) {
                        return true;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * @return 含有aaaa, 1111等连续字符串 返回true
     * @brief 评估aaaa, 1111这样的相同连续字符
     * @param[in] password            密码字符串
     */
    public static boolean checkSequentialSameChars(String password) {
        String t_password = new String(password);
        int n = t_password.length();
        char[] pwdCharArr = t_password.toCharArray();
        boolean flag = false;
        int limit_num = Integer.parseInt(PasswordCheckConfig.LIMIT_NUM_SAME_CHAR);
        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;
    }

    /**
     * 检测常用词库
     *
     * @param password
     * @return
     */
    public static boolean checkSimpleWord(String password) {
        List<String> simpleWords = Arrays.asList(PasswordCheckConfig.SIMPLE_WORDS);
        return simpleWords.contains(password.toLowerCase());
    }


}
package com.zpeng.password;

/**
 * @Author: pengziquan
 * @Date: 2022/10/13 11:06
 */
public class PasswordCheckConfig {
    /**
     * 是否检测密码口令长度
     */
    public static String CHECK_PASSWORD_LENGTH = "enable";
    /**
     * 密码最小长度,默认为8
     */
    public static String MIN_LENGTH = "8";
    /**
     * 密码最大长度,默认为20
     */
    public static String MAX_LENGTH = "20";


    /**
     * 是否包含数字
     */
    public static String CHECK_CONTAIN_DIGIT = "enable";


    /**
     * 是否包含字母
     */
    public static String CHECK_CONTAIN_CASE = "enable";

    /**
     * 是否区分大小写
     */
    public static String CHECK_DISTINGGUISH_CASE = "disable";


    /**
     * 是否包含小写字母
     */
    public static String CHECK_LOWER_CASE = "disable";


    /**
     * 是否包含大写字母
     */
    public static String CHECK_UPPER_CASE = "disable";


    /**
     * 是否包含特殊符号
     */
    public static String CHECK_CONTAIN_SPECIAL_CHAR = "enable";
    /**
     * 特殊符号集合
     */
    public static String SPECIAL_CHAR = "!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~";


    /**
     * 是否检测键盘按键横向连续
     */
    public static String CHECK_HORIZONTAL_KEY_SEQUENTIAL = "enable";
    /**
     * 键盘物理位置横向不允许最小的连续个数
     */
    public static String LIMIT_HORIZONTAL_NUM_KEY = "3";


    /**
     * 是否检测键盘按键斜向连续
     */
    public static String CHECK_SLOPE_KEY_SEQUENTIAL = "enable";
    /**
     * 键盘物理位置斜向不允许最小的连续个数
     */
    public static String LIMIT_SLOPE_NUM_KEY = "3";


    /**
     * 是否检测逻辑位置连续
     */
    public static String CHECK_LOGIC_SEQUENTIAL = "enable";
    /**
     * 密码口令中字符在逻辑位置上不允许最小的连续个数
     */
    public static String LIMIT_LOGIC_NUM_CHAR = "3";


    /**
     * 是否检测连续字符相同
     */
    public static String CHECK_SEQUENTIAL_CHAR_SAME = "enable";
    /**
     * 密码口令中相同字符不允许最小的连续个数
     */
    public static String LIMIT_NUM_SAME_CHAR = "3";


    /**
     * 键盘横向方向规则
     */
    public static String[] KEYBOARD_HORIZONTAL_ARR = {"01234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm",};
    /**
     * 键盘斜线方向规则
     */
    public static String[] KEYBOARD_SLOPE_ARR = {"1qaz", "2wsx", "3edc", "4rfv", "5tgb", "6yhn", "7ujm", "8ik,", "9ol.",
            "0p;/", "=[;.", "-pl,", "0okm", "9ijn", "8uhb", "7ygv", "6tfc", "5rdx", "4esz"};


    /**
     * 是否检测常用词库
     */
    public static String CHECK_SIMPLE_WORD = "enable";

    /**
     * 常用词库
     */
    public static String[] SIMPLE_WORDS = {"admin", "szim", "epicrouter", "password", "grouter", "dare", "root", "guest",
            "user", "success", "pussy", "mustang", "fuckme", "jordan", "test", "hunter", "jennifer", "batman", "thomas",
            "soccer", "sexy", "killer", "george", "asshole", "fuckyou", "summer", "hello", "secret", "fucker", "enter",
            "cookie", "administrator",
            // 中国网民常用密码
            "xiaoming", "taobao", "iloveyou", "woaini", "982464",
            // 国外网民常用密码
            "monkey", "letmein", "trustno1", "dragon", "baseball", "master", "sunshine", "ashley", "bailey", "shadow",
            "superman", "football", "michael", "qazwsx"};



}

Hibernate Validator是一种基于注解的校验框架,用于验证JavaBean中的数据。它提供了一种简单易用的方式来确保数据的完整性和一致性,在实际开发中被广泛应用。 下面是一个校验工具类的示例: ```java import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; public class ValidatorUtils { private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验对象 * * @param obj 待校验对象 * @param groups 待校验的组 * @throws Exception 校验不通过,则报Exception异常 */ public static void validateEntity(Object obj, Class<?>... groups) throws Exception { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj, groups); if (!constraintViolations.isEmpty()) { StringBuilder msg = new StringBuilder(); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { msg.append(constraintViolation.getMessage()).append("<br>"); } throw new Exception(msg.toString()); } } } ``` 使用示例: ```java public class User { @NotNull(message = "用户名不能为空") private String username; @NotNull(message = "密码不能为空") private String password; // getter and setter } public class Test { public static void main(String[] args) { User user = new User(); user.setUsername(null); user.setPassword(null); try { ValidatorUtils.validateEntity(user); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意事项: - 需要在JavaBean的属性上添加相应的注解; - 需要在校验工具类中使用`Validation.buildDefaultValidatorFactory().getValidator()`方法获取`Validator`对象; - 可以通过`groups`参数指定需要校验的组,如果不指定,则校验所有组的规则。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值