標籤:sum author sys for ext mod print ret port
最近做了一個系統,涉及到對使用者輸入的社會安全號碼進行校正,減少髒資料傳入幕後處理並降低企業驗證成本,因此在接入層便對輸入資訊做格式強校正。
直接附上代碼,可直接使用。
1 package hope.identitycodecheck.demo; 2 3 import java.text.DateFormat; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 /** 7 * 8 * @author hp 9 * 10 * */11 public class IdentityCodeUtil {12 /**13 * 社會安全號碼校正 (支援18位)14 * 15 * */16 public static boolean checkIdentityCode(String identityCode) {17 if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {18 return false;19 }20 Date d = new Date();21 DateFormat df = new SimpleDateFormat("yyyyMMdd");22 int year = Integer.parseInt(df.format(d));23 if (Integer.parseInt(identityCode.substring(6, 10)) < 1900 || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份,範圍應該在1900-當前年份之間24 return false;25 }26 if (Integer.parseInt(identityCode.substring(10, 12)) < 1 || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份,範圍應該在01-12之間27 return false;28 }29 if (Integer.parseInt(identityCode.substring(12, 14)) < 1 || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期,範圍應該在01-31之間30 return false;31 }32 // 校正第18位33 // S = Sum(Ai * Wi), i = 0, ... , 16 ,先對前17位元字的權求和34 // Ai:表示第i位置上的社會安全號碼碼數字值35 // Wi:表示第i位置上的加權因子36 // Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 237 String[] tempA = identityCode.split("|");38 int[] a = new int[18];39 for (int i = 0; i < tempA.length - 2; i++) {40 a[i] = Integer.parseInt(tempA[i + 1]);41 }42 int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加權因子43 int sum = 0;44 for (int i = 0; i < 17; i++) {45 sum = sum + a[i] * w[i];46 }47 // Y = mod(S, 11)48 // 通過模得到對應的校正碼49 // Y: 0 1 2 3 4 5 6 7 8 9 1050 // 校正碼: 1 0 X 9 8 7 6 5 4 3 251 String[] v = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校正碼52 int y = sum % 11;53 if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校正碼錯誤54 return false;55 }56 return true;57 }58 59 60 public static void main(String[] args) {61 System.out.println(checkIdentityCode("110110198001019719"));62 }63 }
希望可以為大家提供方便和協助。
Java進行身份證格式強校正(准)