java 身份证验证


工作笔记

public static void isIdCard(String idCard){
int interval = 120;
String cert = idCard;
if(idCard.length() == 15){
System.out.println("传入15位长度证件号:"+idCard);
cert = change15to18(idCard);
System.out.println("转换成18位长度证件号:"+cert);
}
if(cert.length()==18){
if((cert.indexOf("X")>0 && cert.indexOf("X")!=17)||(cert.indexOf("x")>0 && cert.indexOf("x")!=17)){
System.out.println("身份证格式错误");
return;
}
Calendar cal = Calendar.getInstance();
int sysY = cal.get(Calendar.YEAR);
int y = Integer.parseInt(cert.substring(6, 10));
if(y<(sysY-interval) || y>(sysY+interval)){
System.out.println("证件的年度非法");
return;
}
int m = Integer.parseInt(cert.substring(10,12));
if(m<=0 || m>12){
System.out.println("证件的月度非法");
return;
}
int d = Integer.parseInt(cert.substring(12, 14));
if(d<=0 || d>31){
System.out.println("证件的日度非法");
return;
}
if(cert.substring(17)=="x"||cert.substring(17)=="X"){
if(!getVerifyBit(cert).equalsIgnoreCase("x")){
System.out.println("证件非法,最后一位不为x");
}
return;
}else{
if(!cert.substring(17).equals(getVerifyBit(cert))){
System.out.println("证件非法,校验位不正确");
return;
}
}
System.out.println("证件合法");
}
}
//计算校验位(最后一位)
private static String getVerifyBit(String idCard){
int[] wi = new int[]{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
String[] vi = {"1","0","x","9","8","7","6","5","4","3","2"};
int[] ai = new int[idCard.length()];
idCard = idCard.substring(0,17);
for(int i=0;i<idCard.length();i++){
ai[i]= Integer.parseInt(idCard.substring(i, i+1));
}
int num = 0;
for(int i=0;i<17;i++){
num += ai[i]*wi[i];
}
int remaining = num % 11;
return remaining==2?"x":vi[remaining];
}
private static String change15to18(String idCard15){
String idCard = "";
idCard = idCard15.substring(0,6) + "19";
idCard = idCard+idCard15.substring(6, 15);
idCard = idCard + getVerifyBit(idCard);
return idCard;
}

你可能感兴趣的:(杂类)