身份证验证

来源:互联网 发布:mac 移除桌面图标 编辑:程序博客网 时间:2024/04/26 22:17
  1. import java.util.*;   
  2.   
  3. public class Certificate {   
  4.   
  5.   public static final int[] IW = {7910584216379105842};   
  6.   public static final char[] szVerCode = {'1''0''X''9''8''7''6''5''4''3''2'};   
  7.   
  8.   /**  
  9.    * 校验身份证号码的合法性  
  10.    * @param str String  
  11.    * @return boolean  
  12.    */  
  13.   public static boolean valid(String str) {   
  14.     // 字符串不能是null   
  15.     if (str == null) {   
  16.       return false;   
  17.     }   
  18.     // 去掉前后空格等无用字符   
  19.     str = str.trim();   
  20.     // 身份证只允许15位或18位   
  21.     if (str.length() != 15 && str.length() != 18) {   
  22.       return false;   
  23.     }   
  24.     // 暂时不判断15位的情况   
  25.     if (str.length() == 15) {   
  26.       return true;   
  27.     } else {   
  28.       // 判断18位号码的校验位   
  29.       return str.charAt(17) == getVerifyCode(str);   
  30.     }   
  31.   }   
  32.   
  33.   /**  
  34.    * 根据字符串的前17位计算校验位  
  35.    * @param str String 字符串,至少17位长度  
  36.    * @return char 校验位(第18位)  
  37.    */  
  38.   public static char getVerifyCode(String str) {   
  39.     if (str != null && str.length() >= 17) {   
  40.       int IS = 0;   
  41.       for (int i = 0; i < 17; i++) {   
  42.         IS += (str.charAt(i) - '0') * IW[i];   
  43.       }   
  44.       return szVerCode[IS % 11];   
  45.     } else {   
  46.       return '-';   
  47.     }   
  48.   }   
  49.   
  50.   /**  
  51.    * 读取身份证号码的生日信息  
  52.    * @param str String 身份证号码  
  53.    * @return Date 返回日期,如果不合法则返回null  
  54.    */  
  55.   public static Date getBirthday(String str) {   
  56.     if (valid(str)) {   
  57.       String birthday = str.length()==15?("19"+str.substring(6,12)):(str.substring(6,14));   
  58.       return DateTools.parse(birthday,"yyyyMMdd");   
  59.     } else {   
  60.       return null;   
  61.     }   
  62.   }   
  63.   
  64.   /**  
  65.    * 返回身份证号码的性别信息  
  66.    * @param str String 身份证号码  
  67.    * @return int 返回1=男性,0=女性;-1=不合法  
  68.    */  
  69.   public static int getGender(String str) {   
  70.     if(valid(str)){   
  71.       return (str.length()==15?str.charAt(14):str.charAt(16))%2==1?1:0;   
  72.     }else{   
  73.       return -1;   
  74.     }   
  75.   }   
  76. }