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);
}
}
身份证校验算法
最新推荐文章于 2024-07-31 09:39:39 发布