package test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 社會安全號碼碼驗證 * */ public class IdentificationCodeUtil { public static final int IDENTITYCODE_OLD = 15; // 老身份證15位 public static final int IDENTITYCODE_NEW = 18; // 新身份證18位 public static int[] Wi = new int[17]; /** * 判斷社會安全號碼碼是否正確。 * * @param code * 社會安全號碼碼。 * @return 如果社會安全號碼碼正確,則返回true,否則返回false。 */ public static boolean isIdentityCode(String code) { if (StringUtil.empty(code)) { return false; } String birthDay = ""; code = code.trim(); // 長度只有15和18兩種情況 if ((code.length() != IDENTITYCODE_OLD) && (code.length() != IDENTITYCODE_NEW)) { return false; } // 社會安全號碼碼必須為數字(18位的新身份證最後一位可以是x) Pattern pt = Pattern.compile("//d{15,17}([//dxX]{1})?"); Matcher mt = pt.matcher(code); if (!mt.find()) { return false; } // 驗證生日 if (code.length() == IDENTITYCODE_OLD) { birthDay = "19" + code.substring(6, 12); } else { birthDay = code.substring(6, 14); } if (!TimeUtil.isRightDate(birthDay, "yyyyMMdd")) { return false; } // 最後一位校正碼驗證 if (code.length() == IDENTITYCODE_NEW) { String lastNum = getCheckFlag(code.substring(0, IDENTITYCODE_NEW - 1)); // check last digit if (!("" + code.charAt(IDENTITYCODE_NEW - 1)).toUpperCase().equals( lastNum)) { return false; } } return true; } /** * 擷取新身份證的最後一位:檢驗位 * * @param code * 18位身份證的前17位 * @return 新身份證的最後一位 */ private static String getCheckFlag(String code) { int[] varArray = new int[code.length()]; String lastNum = ""; int numSum = 0; // 初始化位權值 setWiBuffer(); for (int i = 0; i < code.length(); i++) { varArray[i] = NumberUtil.toInt("" + code.charAt(i)); varArray[i] = varArray[i] * Wi[i]; numSum = numSum + varArray[i]; } int checkDigit = 12 - numSum % 11; switch (checkDigit) { case 10: lastNum = "X"; break; case 11: lastNum = "0"; break; case 12: lastNum = "1"; break; default: lastNum = String.valueOf(checkDigit); } return lastNum; } /** * 初始化位權值 */ private static void setWiBuffer() { for (int i = 0; i < Wi.length; i++) { int k = (int) Math.pow(2, (Wi.length - i)); Wi[i] = k % 11; } } /** * 判別是否字串為null或者沒有內容,或者全部為空白格。 */ public static boolean empty(String o) { return ((null == o) || (o.length() <= 0) || (o.trim().equals(""))); } /** * 將15位社會安全號碼碼升級為18位社會安全號碼碼 * * @param code * 15位社會安全號碼碼 * @return 18位社會安全號碼碼 */ public static String update2eighteen(String code) { if (StringUtil.empty(code)) { return ""; } code = code.trim(); if (code.length() != IDENTITYCODE_OLD || !isIdentityCode(code)) { return ""; } code = code.substring(0, 6) + "19" + code.substring(6); // code = code + getCheckFlag(code); return code; } public static void main(String[] args){ String[] codeArray = new String[]{"330521197411044030","53010119810602007x","53010119810602001x"}; for(int i= 0;i<codeArray.length;i++){ if(isIdentityCode(codeArray[i])){ System.out.println(codeArray[i]+":為正確的社會安全號碼碼。"); }else{ System.out.println(codeArray[i]+":為錯誤的社會安全號碼碼。"); } } System.out.println("轉換後的社會安全號碼碼為:"+update2eighteen("330521820721052"));; } }