把自己做的工具类留个档,同时分享给大家
/** * 将旧的15位身份证件号,转成18位, * 同时进行身份证信息的简单校验 * 如果是18位,则只进行校验 * @param orgIDCardNo * @return * @throws ParseException 身份证校验异常 */ public static String converse15DigitTo18Digit(String orgIDCardNo) throws ParseException{ if(orgIDCardNo == null){ throw new IllegalArgumentException("身份证号为null"); } String buffer = orgIDCardNo.trim(); int numberLength = buffer.length(); //校验身份证位数,如果不是15位或18位,则抛出“IllgalArgumentException非法的证件号码”异常 if(numberLength != 15 && numberLength != 18){ throw new ParseException("不合格的身份证号" , 0); } //校验身份证的日期参数 if(numberLength == 15){ //校验15位身份证的日期参数 String birthDateStr = buffer.substring(6 , 12); try { new SimpleDateFormat("yyMMdd").parse(birthDateStr); } catch (ParseException e) { e.printStackTrace(); throw new ParseException("不合格的身份证号" , 7); } //对15位的证件转换18位的前缀部分 buffer = buffer.substring(0,6) + "19" + buffer.substring(6 , 15); }else{ //校验18位身份证的日期参数 String birthDateStr = buffer.substring(6 , 14); try { new SimpleDateFormat("yyyyMMdd").parse(birthDateStr); } catch (ParseException e) { e.printStackTrace(); throw new ParseException("不合格的身份证号" , 7); } //截取前17位,对18位证件进行尾部编码重计算 buffer = buffer.substring(0,17); } //计算18位证的校验位 char[] charArray = buffer.toCharArray(); int factor = 0; for(int i = 18 ; i>=2 ; i--){ if(charArray[18 - i] < '0' || charArray[18 - i] > '9'){ throw new ParseException("不合格的身份证号" , 18-i); } factor += (((int)Math.pow(2, (i-1))) % 11) *((charArray[18 - i] & 0xff) - 48); } factor %= 11; switch(factor){ case 0 : buffer += "1"; break; case 1 : buffer += "0"; break; case 2 : buffer += "X"; break; case 3 : buffer += "9"; break; case 4 : buffer += "8"; break; case 5 : buffer += "7"; break; case 6 : buffer += "6"; break; case 7 : buffer += "5"; break; case 8 : buffer += "4"; break; case 9 : buffer += "3"; break; case 10 : buffer += "2"; break; } //如果是18位的身份证,要同原始的证件代码进行校验 if(numberLength == 18 && !buffer.equals(orgIDCardNo.trim())){ throw new ParseException("不合格的身份证号" , 18); } return buffer; }