Java ID card legality verification and obtain valid information of the ID card number for your reference. The specific content is as follows
Java ID card legality verification
/**The first 6 digits of the ID card [ABCDEF] are administrative division digital codes (refer to the digital code for short) description (refer to the "GB/T 2260-2007 Administrative Division Code of the People's Republic of China"): * The principle and structure analysis of the compilation of this digital code adopts a three-layer six-digit hierarchical code structure, which represents the provinces (autonomous regions, municipalities directly under the central government, special administrative regions), * cities (regions, autonomous prefectures, leagues), and counties (autonomous counties, county-level cities, banners, autonomous banners, municipal districts, forest areas, special districts) in China according to the hierarchy. The meaning of the digital code code structure from left to right is: The first layer is AB two-digit code that represents the province, autonomous region, municipality directly under the central government, and special administrative regions; the second layer is CD two-digit code that represents the summary code of the municipality, region, autonomous prefecture, alliance, and municipality directly under the central government, and the summary code of the county-level administrative divisions directly under the provincial (autonomous region), among which: ―01~20, 51~70 represents the city, 01, 02 is also used to represent the summary code of the municipality directly under the central government; ―21~50 represents the summary code of the district, autonomous prefecture, alliance; ―90 represents the summary code of the county-level administrative divisions directly under the provincial (autonomous region). The third floor is the two EF digits representing counties, autonomous counties, county-level cities, banners, autonomous banners, municipal districts, forest areas, and special districts. Among them: ―01~20 represents county-level cities with county-level cities under the jurisdiction of the city, districts (autonomous prefectures, leagues) and county-level cities under the county-level administrative divisions directly under the jurisdiction of the province (autonomous region). 01 usually represents the summary code of the jurisdiction; ―21~80 represents county-level cities under the jurisdiction of counties, autonomous counties, banners, autonomous banners, forest areas, and regional special districts; ―81~99 represents county-level cities under the jurisdiction of the province (autonomous region). */import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.Map;import java.util.regex.Pattern;/** * <p> * Class Description: ID card legality verification* </p> * <p> * --15-digit ID number: 7th and 8th digits are the year of birth (double digits), 9th and 10th digits are the month of birth, 11th and 12th digits represent the date of birth, 15th digits represent the gender, odd numbers are males, and even numbers are females. * --18-digit ID number*: 7, 8, 9, and 10 are the year of birth (four digits), 11 and 12 are the month of birth, 13 and 14 represent the date of birth, 17 represent the gender, odd numbers are male, and even numbers are female. * </p> */@SuppressWarnings({ "unchecked", "unused", "all" })public class IdcardValidator { /** * Provincial, municipal code table: { 11:"Beijing", 12:"Tianjin", 13:"Hebei", 14:"Shanxi", 15:"Inner Mongolia", * 21:"Liaoning", 22:"Jilin", 23:"Heilongjiang", 31:"Shanghai", 32:"Jiangsu", * 33:"Zhejiang", 34:"Anhui", 35:"Fujian", 36:"Jiangxi", 37:"Shandong", 41:"Henan", * 42:"Hubei",43:"Hunan",44:"Guangdong",45:"Guangxi",46:"Hainan",50:"Chongqing", * 51:"Sichuan",52:"Guizhou",53:"Yunnan",54:"Tibet",61:"Shaanxi",62:"Gansu", * 63:"Qinghai",64:"Ningxia",65:"Xinjiang",71:"Taiwan",81:"Hong Kong",82:"Macao",91:"Foreign"} */ protected String codeAndCity[][] = { { "11", "Beijing" }, { "12", "Tianjin" }, { "13", "Hebei" }, { "14", "Shanxi" }, { "15", "Inner Mongolia" }, { "21", "Liaoning" }, { "22", "Jilin" }, { "23", "Heilongjiang" }, { "31", "Shanghai" }, { "32", "Jiangsu" }, { "33", "Zhejiang" }, { "34", "Anhui" }, { "35", "Fujian" }, { "36", "Jiangxi" }, { "37", "Shandong" }, { "41", "Henan" }, { "42", "Hubei" }, { "43", "Hunan" }, { "44", "Guangdong" }, { "45", "Guangxi" }, { "46", "Hainan" }, { "50", "Chongqing" }, { "51", "Sichuan" }, { "52", "Guizhou" }, { "53", "Yunnan" }, { "54", "Tibet" }, { "61", "Shaanxi" }, { "62", "Gansu" }, { "63", "Qinghai" }, { "64", "Ningxia" }, { "65", "Xinjiang" }, { "71", "Taiwan" }, { "81", "Hong Kong" }, { "82", "Macao" }, { "91", "Foreign" } }; private String cityCode[] = { "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91" }; // Each weighting factor private int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 18th bit verification code private String verifyCode[] = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; /** * Verify the legality of all ID cards* * @param idcard * @return */ public boolean isValidatedAllIdcard(String idcard) { if (idcard.length() == 15) { idcard = this.convertIdcarBy15bit(idcard); } return this.isValidate18Idcard(idcard); } /** * <p> * Determine the legality of an 18-digit ID card* </p> * According to the provisions on citizenship ID numbers in the National Standard GB11643-1999 of the People's Republic of China, the citizenship ID number is a feature combination code, consisting of a seventeen-digit digital ontology code and a one-digit verification code. * The arrangement order is from left to right: six-digit address code, eight-digit date of birth code, three-digit sequence code and one-digit verification code. * <p> * Sequence code: Indicates the sequence number assigned to people born in the same year, month, and day within the area identified by the same address code. The odd number of the sequence code is assigned to men and even number is assigned to women. * </p> * <p> * 1. The first 1 and 2 digits represent: the code of the province; 2. The 3rd and 4th digits represent: the code of the city; 3. The 5th and 6th digits represent: the code of the district and county; * 4. The 7th to 14th digits represent: the year, month, day of birth; 5. The 15th and 16th digits represent: the code of the police station in the location; * 6. The 17th digits represent gender: odd numbers represent males, and even numbers represent females; * 7. The 18th digit is the proofreading code: some say it is a personal information code, which is generally generated randomly by the computer to check the correctness of the ID card. The calibration code can be a number from 0 to 9, and sometimes it is also represented by x. * </p> * <p> * The calculation method of the eighteenth digit (check code) is: 1. Multiply the 17-digit number of the previous ID number by different coefficients. The coefficients from the first digit to the seventeenth digit are: 7 9 10 5 8 4 * 2 1 6 3 7 9 10 5 8 4 2 * </p> * <p> * 2. Add the result of multiplying these 17-digit numbers and coefficients. * </p> * <p> * 3. Use the addition and divide by 11 to see what the remainder is? * </p> * 4. The remainder can only have 11 numbers 0 1 2 3 4 5 6 7 8 9 10. The number of the last ID card corresponding to each is 1 0 X 9 8 7 6 5 4 3 * 2. * <p> * 5. From the above, if the remainder is 2, the Ⅹ of the Roman numeral will appear on the 18th digit of the ID card. If the remainder is 10, the last number of the ID card is 2. * </p> * * @param idcard * @return */ public boolean isValidate18Idcard(String idcard) { // Non-18 bits are false if (idcard.length() != 18) { return false; } // Get the first 17 bits String idcard17 = idcard.substring(0, 17); // Get the 18th bit String idcard18Code = idcard.substring(17, 18); char c[] = null; String checkCode = ""; // Are all numbers if (isDigital(idcard17)) { c = idcard17.toCharArray(); } else { return false; } if (null != c) { int bit[] = new int[idcard17.length()]; bit = converCharToInt(c); int sum17 = 0; sum17 = getPowerSum(bit); // Check the sum value with 11 to get the remainder for verification code checkCode = getCheckCodeBySum(sum17); if (null == checkCode) { return false; } // Match the 18th bit of the ID card with the calculated calibration code. If it is not equal, it is a false if (!idcard18Code.equalsIgnoreCase(checkCode)) { return false; } } return true; } /** * Verify the legality of the 15-bit ID card. This method is inaccurate. It is best to convert 15 to 18-bit before judging, which has been provided in this class. * * @param idcard * @return */ public boolean isValidate15Idcard(String idcard) { // Non-15 bits are false if (idcard.length() != 15) { return false; } // Are all numbers if (isDigital(idcard)) { String provinceid = idcard.substring(0, 2); String birthday = idcard.substring(6, 12); int year = Integer.parseInt(idcard.substring(6, 8)); int month = Integer.parseInt(idcard.substring(8, 10)); int day = Integer.parseInt(idcard.substring(10, 12)); // Determine whether it is a legal province boolean flag = false; for (String id : cityCode) { if (id.equals(provinceid)) { flag = true; break; } } if (!flag) { return false; } // The birth date of this ID card is false after the current date Date birthdate = null; try { birthdate = new SimpleDateFormat("yyMMdd").parse(birthday); } catch (ParseException e) { e.printStackTrace(); } if (birthdate == null || new Date().before(birthdate)) { return false; } // To determine whether it is a legal year GregorianCalendar curDay = new GregorianCalendar(); int curYear = curDay.get(Calendar.YEAR); int year2bit = Integer.parseInt(String.valueOf(curYear) .substring(2)); // } // To determine whether it is a legal month if (month < 1 || month > 12) { return false; } // To determine whether it is a legal date boolean mflag = false; curDay.setTime(birthdate); // Assign the date of birth of this ID card to the object curDay switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: mflag = (day >= 1 && day <= 31); break; case 2: // There are 28 days in the February of the Gregorian calendar, and 29 days in the February of the leap year. if (curDay.isLeapYear(curDay.get(Calendar.YEAR))) { mflag = (day >= 1 && day <= 29); } else { mflag = (day >= 1 && day <= 28); } break; case 4: case 6: case 9: case 11: mflag = (day >= 1 && day <= 30); break; } if (!mflag) { return false; } } else { return false; } return true; } /** * Convert a 15-digit ID card to a 18-digit ID card* * @param idcard * @return */ public String convertIdcarBy15bit(String idcard) { String idcard17 = null; // Non-15-bit ID card if (idcard.length() != 15) { return null; } if (isDigital(idcard)) { // Get the date of birth String birthday = idcard.substring(6, 12); Date birthdate = null; try { birthdate = new SimpleDateFormat("yyMMdd").parse(birthday); } catch (ParseException e) { e.printStackTrace(); } Calendar cday = Calendar.getInstance(); cday.setTime(birthdate); String year = String.valueOf(cday.get(Calendar.YEAR)); idcard17 = idcard.substring(0, 6) + year + idcard.substring(8); char c[] = idcard17.toCharArray(); String checkCode = ""; if (null != c) { int bit[] = new int[idcard17.length()]; // Convert the character array into an integer array bit = converCharToInt(c); int sum17 = 0; sum17 = getPowerSum(bit); // Get the sum value and get the remainder to check the code checkCode = getCheckCodeBySum(sum17); // Cannot get the check bit if (null == checkCode) { return null; } // Splice the first 17 digits with the 18th digit check code idcard17 += checkCode; } } else { // The ID card contains the number return null; } return idcard17; } /** * Basic numerical and digit check of 15-bit and 18-bit ID card numbers* * @param idcard * @return */ public boolean isIdcard(String idcard) { return idcard == null || "".equals(idcard) ? false : Pattern.matches( "(^//d{15}$)|(//d{17}(?://d|x|X)$)", idcard); } /** * Basic digits and digits checks for 15-digit ID numbers* * @param idcard * @return */ public boolean is15Idcard(String idcard) { return idcard == null || "".equals(idcard) ? false : Pattern.matches( "^[1-9]//d{7}(0//d)|(1[0-2]))(([0|1|2]//d)|3[0-1])//d{3}$", idcard); } /** * Basic numbers and digits checks for 18-digit ID number* * @param idcard * @return */ public boolean is18Idcard(String idcard) { return Pattern .matches( "^[1-9]//d{5}[1-9]//d{3}((0//d)|(1[0-2]))(([0|1|2]//d)|3[0-1])//d{3}([//d|x|X]{1})$", idcard); } /** * Digital verification* * @param str * @return */ public boolean isDigital(String str) { return str == null || "".equals(str) ? false : str.matches("^[0-9]*$"); } /** * Multiply each bit of the ID card and the weighting factor of the corresponding bit, and then get the sum value* * @param bit * @return */ public int getPowerSum(int[] bit) { int sum = 0; if (power.length != bit.length) { return sum; } for (int i = 0; i < bit.length; i++) { for (int j = 0; j < power.length; j++) { if (i == j) { sum = sum + bit[i] * power[j]; } } } return sum; } /** * Check the sum value with 11 to get the remainder for verification code* * @param checkCode * @param sum17 * @return check bit*/ public String getCheckCodeBySum(int sum17) { String checkCode = null; switch (sum17 % 11) { case 10: checkCode = "2"; break; case 9: checkCode = "3"; break; case 8: checkCode = "4"; break; case 7: checkCode = "5"; break; case 6: checkCode = "6"; break; case 5: checkCode = "7"; break; case 4: checkCode = "8"; break; case 3: checkCode = "9"; break; case 2: checkCode = "x"; break; case 1: checkCode = "0"; break; case 0: checkCode = "1"; break; } return checkCode; } /** * Convert a character array into an integer array* * @param c * @return * @throws NumberFormatException */ public int[] converCharToInt(char[] c) throws NumberFormatException { int[] a = new int[c.length]; int k = 0; for (char temp : c) { a[k++] = Integer.parseInt(String.valueOf(temp)); } return a; } public static void main(String[] args) throws Exception { String idcard15 = "142431199001145";//15-bit String idcard18 = "12121212121212121212121212";//18-bit IdcardValidator iv = new IdcardValidator(); System.out.println(iv.isValidatedAllIdcard(idcard15)); System.out.println(iv.isValidatedAllIdcard(idcard18)); }}Extract information related to ID card based on ID card number
import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.Map;import java.util.Set;/** * <p> * Class Description: Extract information related to ID card* </p> */public class IdcardInfoExtractor { // Province private String province; // City private String city; // District and county private String region; // Year private int year; // month private int month; // date private int day; // gender private String gender; // date of birth private Date birthday; private Map<String, String> cityCodeMap = new HashMap<String, String>() { { this.put("11", "Beijing"); this.put("12", "Tianjin"); this.put("13", "Hebei"); this.put("14", "Shanxi"); this.put("15", "Inner Mongolia"); this.put("21", "Liaoning"); this.put("22", "Jilin"); this.put("23", "Heilongjiang"); this.put("31", "Shanghai"); this.put("32", "Jiangsu"); this.put("33", "Zhejiang"); this.put("34", "Anhui"); this.put("35", "Fujian"); this.put("36", "Jiangxi"); this.put("37", "Shandong"); this.put("41", "Henan"); this.put("42", "Hubei"); this.put("43", "Hunan"); this.put("44", "Guangdong"); this.put("45", "Guangxi"); this.put("46", "Hainan"); this.put("50", "Chongqing"); this.put("51", "Sichuan"); this.put("52", "Guizhou"); this.put("53", "Yunnan"); this.put("54", "Tibet"); this.put("61", "Shaanxi"); this.put("62", "Gansu"); this.put("63", "Qinghai"); this.put("64", "Ningxia"); this.put("65", "Xinjiang"); this.put("71", "Taiwan"); this.put("81", "Hong Kong"); this.put("82", "Macao"); this.put("91", "Foreign"); } }; private IdcardValidator validator = null; /** * Initialize each member attribute through a constructor*/ public IdcardInfoExtractor(String idcard) { try { validator = new IdcardValidator(); if (validator.isValidatedAllIdcard(idcard)) { if (idcard.length() == 15) { idcard = validator.convertIdcarBy15bit(idcard); } // Get the province String provinceId = idcard.substring(0, 2); Set<String> key = this.cityCodeMap.keySet(); for (String id : key) { if (id.equals(provinceId)) { this.province = this.cityCodeMap.get(id); break; } } // Get the gender String id17 = idcard.substring(16, 17); if (Integer.parseInt(id17) % 2 != 0) { this.gender = "Male"; } else { this.gender = "Female"; } // Get the date of birth String birthday = idcard.substring(6, 14); Date birthdate = new SimpleDateFormat("yyyyMMdd") .parse(birthday); this.birthday = birthday; GregorianCalendar currentDay = new GregorianCalendar(); currentDay.setTime(birthdate); this.year = currentDay.get(Calendar.YEAR); this.month = currentDay.get(Calendar.MONTH) + 1; this.day = currentDay.get(Calendar.DAY_OF_MONTH); } } catch (Exception e) { e.printStackTrace(); } } /** * @return the province */ public String getProvince() { return province; } /** * @return the city */ public String getCity() { return city; } /** * @return the region */ public String getRegion() { return region; } /** * @return the year */ public int getYear() { return year; } /** * @return the month */ public int getMonth() { return month; } /** * @return the day */ public int getDay() { return day; } /** * @return the gender */ public String getGender() { return gender; } /** * @return the birthday */ public Date getBirthday() { return birthday; } @Override public String toString() { return "Province: " + this.province + ",Gender: " + this.gender + ",Date of birth: " + this.birthday; } public static void main(String[] args) { String idcard = "1212121212121212121212"; IdcardInfoExtractor ie = new IdcardInfoExtractor(idcard); System.out.println(ie.toString()); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.