身份证校验算法

package util;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by LiuWenSheng on 2018/1/11.
 */
public class CheckIdCard {
    private final static int NEW_CARD_NUMBER_LENGTH = 18;
    private final static char[] VERIFY_CODE = { '1', '0', 'X', '9', '8', '7','6', '5', '4', '3', '2' }; // 18位身份证中最后一位
    private final static int[] VERIFY_CODE_WEIGHT = { 7, 9, 10, 5, 8, 4, 2, 1,6, 3, 7, 9, 10, 5, 8, 4, 2 };// 18位身份证中,各个数字的生成校验码时的权值

    public  static boolean validate(String cardNumber) {
        String birthDayPart = cardNumber.substring(6, 14);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        boolean result = true;


        result = result && (calculateVerifyCode(cardNumber) == cardNumber.charAt(NEW_CARD_NUMBER_LENGTH - 1));
            // 出生日期不能晚于当前时间,并且不能早于1900年
            try {
                Date birthDate = format.parse(birthDayPart);
                result = result && null != birthDate;
                result = result && birthDate.before(new Date());
                result = result && birthDate.after(new Date(-2209017600000L));
                /**
                 * 出生日期中的年、月、日必须正确,比如月份范围是[1,12],日期范围是[1,31],还需要校验闰年、大月、小月的情况时,
                 * 月份和日期相符合
                 */
                String birthdayPart = birthDayPart;
                String realBirthdayPart = format.format(birthDate);
                result = result && (birthdayPart.equals(realBirthdayPart));
            } catch (Exception e) {
                result = false;
            }

        return Boolean.valueOf(result);
    }


    /**
     * 检验第18位
     *
     * 根据公式 S = Sum(Ai * Wi), i = 0...16 ,先对前17位数字的权求和;
     * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
     * 2; 计算模 Y = mod(S, 11)< 通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9
     * 8 7 6 5 4 3 2
     *
     * @param cardNumber
     * @return
     */
    private static char calculateVerifyCode(CharSequence cardNumber) {
        int sum = 0;
        for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
            char ch = cardNumber.charAt(i);
            sum += ((int) (ch - '0')) * VERIFY_CODE_WEIGHT[i];
        }
        return VERIFY_CODE[sum % 11];
    }


    public static  void main(String[] args){
        boolean b = CheckIdCard.validate("110226198501242116");

        System.out.println(b);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天心有情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值