开发手册 欢迎您!
软件开发者资料库

Java 生成六位验证码、SQL关键字验证、身证号和手机号脱敏工具类

本文主要介绍Java中,随机生成六位验证码、过滤掉的sql关键字的验证方法、身证号和手机号脱敏处理成*号的工具类,还有从身份证中提取生日,以及相关的示例代码。
package com.wonhero.utils.util;import org.apache.commons.lang3.math.NumberUtils;import org.springframework.util.StringUtils;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;/** * 验证码、手机号、身份证号处理工具类 */public class CommonUtil extends LoggerEngine {    /**     * 生成六位验证码     *     * @return     */    public static String generateVerificationCode() {        Random random = new Random();        String result = "";        for (int i = 0; i < 6; i++) {            result += (random.nextInt(9) + 1);;        }        return result;    }    // 手机号码前三后四脱敏    public static String mobileEncrypt(String mobile) {        if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {            return mobile;        }        return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");    }    //身份证前三后四脱敏    public static String idEncrypt(String id) {        if (StringUtils.isEmpty(id) || (id.length() < 8)) {            return id;        }        return id.replaceAll("(?<=\\w{3})\\w(?=\\w{4})", "*");    }    //效验    public static boolean sqlValidate(String str) {        str = str.toLowerCase();//统一转为小写        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +                "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +                "table|from|grant|use|group_concat|column_name|" +                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +                "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";//过滤掉的sql关键字,可以手动添加        String[] badStrs = badStr.split("\\|");        for (int i = 0; i < badStrs.length; i++) {            if (str.indexOf(badStrs[i]) >= 0) {                return true;            }        }        return false;    }    /**     * 根据身份证号获取年龄     * @param certId     * @return     */    public static String getAgeByCertId(String certId) {        String birthday = "";        if (certId.length() == 18) {            birthday = certId.substring(6, 10) + "/"                    + certId.substring(10, 12) + "/"                    + certId.substring(12, 14);        }        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");        Date now = new Date();        Date birth = new Date();        try {            birth = sdf.parse(birthday);        } catch (ParseException e) {        }        long intervalMilli = now.getTime() - birth.getTime();        int age = (int) (intervalMilli/(24 * 60 * 60 * 1000))/365;        System.out.println(age);        return age +"";    }}
cript>