The legitimacy of the new and old ID card verification and validation algorithm

sponsored links
1. Chinese citizen ID card common sense:

China's current use of citizen identity card numbers, there are two standards for the two countries can follow,] [GB 11643-1989 and GB 11643-1999] [.

GB 11643-1989] [specified ID number is 15: in the order from left to right: the six-digit address code, six-digit date of birth, code, three-digit sequence code, which does not include date of birth code Number century.


6 administrative division code


6 Date of Birth


3 order code





] [GB 11643-1999 is provided for 18-bit ID number: citizenship is a characteristic combination of code numbers from 17 yards and a digital body composed of digital check code. In the order from left to right: the six-digit address code, the eight-digit date of birth, code, order code and a three-digit code number check.


6 administrative division code


6 Date of Birth


3 order code


A check code



Administrative division of the code: code object that permanent residence county (city, flag) of the administrative area.

Administrative division code [] national standard GB T 2260-1999

Date of birth code: code object that was born of the year, month, day, of which four-digit year that year, month, and Japan do not have a separator.

Order code: code that identified the same address within the area, on the same year, the same month, the same date of birth of staff scheduled sequence number. The odd order code assigned to men, even women were given.

Checksum: 17 figures are based on the previous code, in accordance with ISO 7064:1983. MOD 11-2 checksum calculated from the test code.

ISO 7064:1983. MOD 11-2 checksum calculation

The People's Republic of China in accordance with the provisions of the national standard GB11643-1999 The People's Republic of China citizenship, number of checksum calculation shall be ISO 7064:1983. MOD 11-2 checksum calculation.

Figures assume a 17

17 figures 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
Weighting factor 2 4 8 5 10 9 7 3 6 1 2 4 8 5 10 9 7
  1. Computing 17 numbers you figure with the corresponding weighting factor of the product and S: 1 X 2 + 2 × 4 +3 × 8 + 4 × 5 +5 × 10 + 6 × 9 +7 × 7 + 8 × 3 +9 × 6 + 0 × 1 +1 X 2 + 2 × 4 +3 × 8 + 4 × 5 +5 × 10 + 6 × 9 +7 × 7 = 492;
  2. Calculate the remainder of S ÷ 11 T: 492 mod 11 = 8;
  3. Calculation (12-T) ÷ 11 the remainder R, if R = 10, validation code for the letter "X"; If R ≠ 10, parity check codes for digital "R": (12-8) mod 11 = 4.

The 17-digit verification code is 4, polymerization in the 12345678901234567 4.

package id_card;

import string_util.StringUtil;

/**
 *  The identity card number verification applet  
 * @author Kevin
 * 2010-3-28
 */
public class IdCardUtil {
        /**  The old ID card number digits  ( There are numbers  ) */
        public static final int OLD_IDCARD_LEN=15;
        /**  The new identity card numbers of digits   */
        public static final int NEW_IDCARD_LEN=18;
        /**  Hold the right of the value array   */
        private static int[] wi=new int[17];
    /** Minimum administrative districts in code  */
    private final static int MINCODE = 110000;
    /** Maximum administrative districts in code  */
    private final static int MAXCODE = 820000;
    /**  Modulo parameters   */
    private final static int MODE=11;
    /**  The new ID card year mark   */
    private final static String YEAR_FLAG="19";
    /**
     *  Sets the right value  
     */
    private static void setWiValue(){
        for(int i=0;i<wi.length;i++){
                int k=(int)Math.pow(2, (wi.length-i));
                wi[i]=k%MODE;
        }
    }
    /**
     *  According to the new identity card numbers before 17 as numbers  , Get the last digit of the code  
     * @param checkString
     * @return
     */
    private static String getCheckCode(String checkString){
        int sum=0;
        setWiValue();// Sets the right value  
        for(int i=0;i<checkString.length();i++){
                int k=StringUtil.convertInteger(String.valueOf(checkString.charAt(i)))*wi[i];
                sum+=k;
        }
        int num=(12-(sum%MODE))%MODE;
        if(num==10){
                return "X";
        }else{
                return String.valueOf(num);
        }
        
    }
    /**
     *  Verify that the ID number of the administrative regions of code is valid  
     * @param idCard
     * @return
     */
    public static boolean isValidateCantonCode(String idCard) throws Exception{
        String cantonCode=idCard.substring(0,6);
        int code=StringUtil.convertInteger(cantonCode);
        if(code>=MINCODE && code<=MAXCODE){
                return true;
        }
        return false;
    }
    /**
     *  Verify that the new ID card is valid for the last bit  
     * @param lastLetter
     * @return
     */
        private static boolean isValidateLastCode(String lastCode){
                // Is a number .'x ' or  'X'
                if(StringUtil.isCompleteNumberString(lastCode)||lastCode.equalsIgnoreCase("x")){
                        return true;
                }
                return false;
        }
    /**
     *  Verify that the card is valid  
     * @param idCard
     * @return
     */
    public static boolean isValidateIdCard(String idCard) throws Exception{
        // Verify that a valid string  
        if(!StringUtil.isValidateString(idCard)){
                return false;
        }
        // Remove whitespace before and after  
        idCard=idCard.trim();
        // Verify that the ID number is a 15-bit or  18 Bit  
        if(idCard.length()!=OLD_IDCARD_LEN && idCard.length()!=NEW_IDCARD_LEN){
                return false;
        }
        // Verify that the ID number of the administrative regions of code is valid  
        if(!isValidateCantonCode(idCard)){
                return false;
        }
        // ID card birthday number  
        String birthday="";
        
        if(idCard.length()==OLD_IDCARD_LEN){
                if(StringUtil.isCompleteNumberString(idCard)){
                        birthday=YEAR_FLAG+idCard.substring(6,12);
                }
        }else{
                if(StringUtil.isCompleteNumberString(idCard.substring(0,17))){
                        if(isValidateLastCode(idCard.substring(17, idCard.length()))){
                                birthday=idCard.substring(6, 14);
                        }
                }
        }
        // Verify that the birthday date format is valid  
                if(!StringUtil.isValidateDateString(birthday, "yyyyMMdd")){
                        return false;
                }
                // Verify that the new ID card is valid for the last bit  
                if(idCard.length()==NEW_IDCARD_LEN){
                        String lastCode=getCheckCode(idCard.substring(0,17));
                        if(!(String.valueOf(idCard.charAt(17)).equalsIgnoreCase(lastCode))){
                                return false;
                        }
                }
                
        return true;
    }
    /**
     *  The old ID card number into the new identity card number  
     * @param code
     * @return
     * @throws Exception
     */
        public static String oldCard2newCarid(String oldIdCard) throws Exception{
                if(!StringUtil.isValidateString(oldIdCard)){
                        return "";
                }
                oldIdCard=oldIdCard.trim();
                if(oldIdCard.length()!=OLD_IDCARD_LEN||!isValidateIdCard(oldIdCard)){
                        return "";
                }
                oldIdCard=oldIdCard.substring(0,6)+YEAR_FLAG+oldIdCard.substring(6);
                oldIdCard=oldIdCard+getCheckCode(oldIdCard);
                return oldIdCard;
        }
        /**
         *  Test  
         * @param args
         * @throws Exception
         */
        public static void main(String args[]) throws Exception{
                System.out.println(IdCardUtil.isValidateIdCard("000000000000000000"));
        }
}


package string_util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public final class StringUtil{
        /**
         *  A string array with  
         * @param stringAry  An array of strings  
         * @param joinToken  Delimiter  
         * @return  Merged string  
         */
        public static String join(String []stringAry,String joinToken){
                if(stringAry==null||stringAry.length<=0){
                        return null;
                }
                if(joinToken==null||joinToken.equalsIgnoreCase("null")){
                        joinToken="";
                }
                joinToken=joinToken.trim();
                StringBuffer sb=new StringBuffer();
                for(int i=0;i<stringAry.length;i++){
                        if(i>0){
                                sb.append(joinToken);
                        }
                        sb.append(stringAry[i]);
                }
                return sb.toString();
        }
        /**
         *  An integer to a string into an integer  
         * @param str  The string of digits  
         * @return  Converted the type int.  
         * @throws NumberFormatException
         */
        public static int convertInteger(String str) throws NumberFormatException{
                int number=0;
                if(!isValidateString(str)){
                        return number;
                }
                str=str.trim();
                try {
                        number=Integer.parseInt(str);
                } catch (NumberFormatException e) {
                        throw e;
                }
                return number;
        }
        /**
         *  The floating point number of the string is converted to a floating point number  
         * @param str  A string to be converted  
         * @return  Converted floating-point number  
         * @throws NumberFormatException
         */
        public static float convertFloat(String str)throws NumberFormatException{
                float number=0.0f;
                if(!isValidateString(str)){
                        return number;
                }
                str=str.trim();
                try {
                        number=Float.parseFloat(str);
                } catch (NumberFormatException e) {
                        throw e;
                }
                return number;
        }
        /**
         *  Converts a double-precision floating point number strings to a double-precision floating point number  
         * @param str  A string to be converted  
         * @return  Converted values  
         * @throws NumberFormatException
         */
        public static double convertDouble(String str)throws NumberFormatException{
                double number=0.0;
                if(!isValidateString(str)){
                        return number;
                }
                str=str.trim();
                try {
                        number=Double.parseDouble(str);
                } catch (NumberFormatException e) {
                        throw e;
                }
                return number;
        }
        /**
         *  Verify the legitimacy of a string  ( That is, the string is not able to  null)
         *  This method does not remove spaces in a string  
         * @param str String
         * @return  If NULL is returned  ""
         */
        public static String CheckString(String str){
                if(str==null||str.equalsIgnoreCase("null")){
                        return "";
                }
                /**
                 *  Remove the space before and after  
                 */
                return str.trim();
        }
        /**
         *  Verify the legitimacy of a string  ( The string can be  null)
         *  This method does not remove spaces in a string  
         * @param str String
         * @return  If NULL is returned  ""
         */
        public static String ValidateString(String str){
                if(str==null){
                        return "";
                }
                /**
                 *  Remove the space before and after  
                 */
                return str.trim();
        }
        /**
         *  Verify that a valid string  
         * @param str
         * @return
         */
        public static boolean isValidateString(String str){
                if(str==null){
                        return false;
                }
                if(str.trim().equals("")){
                        return false;
                }
                if(str.equalsIgnoreCase("null")){
                        return false;
                }
                return true;
        }
        /**
         *  From the current string for a character to begin intercepting a string  
         * @param str String
         * @param singleChar String Character mark  
         * @param front boolean  If the value is true table-interception of the character preceding the mark characters  , On the contrary the contrary  
         * @return  Interception string  
         */
        public static String cutString(String str,String singleChar,boolean front){
                if(!isValidateString(str)){
                        return "";
                }
                if(!isValidateString(singleChar)){
                        return "";
                }
                str=str.trim();
                singleChar=singleChar.trim();
                if(str.contains(singleChar)){
                        int index=str.indexOf(singleChar);
                        if(front){
                                return str.substring(0,index);
                        }else{
                                return str.substring(index+1,str.length());
                        }
                }else{
                        return str;
                }
        }
        /**
         *  Remove the database to a string representation of a date  
         *  Into  :1999-09-09 Date format of the form  
         * @param dbStr String
         * @return  String  Converted string  
         */
        public static String toDateString(String dbStr){
                
                if(!isValidateString(dbStr)){
                        return "";
                }
                dbStr=dbStr.trim();
                return dbStr.substring(0,10);
        }
        /**
         *  A string converted to uppercase letters  
         * @param name
         * @return
         */
        public static String toUpperCaseFirstLetter(String name){
                if(!isValidateString(name)){
                        return "";
                }
                name=name.trim();
                if(name.length()>0){
                        return name.substring(0,1).toUpperCase()+name.substring(1);
                }
                return "";
        }
        /**
         *  The JavaBean property name into its  set And the get method name  
         *  The transformation rules are as follows  :(1) The property name of the second letter if you do not have to capitalize the first letter will be converted to upper case  
         * @param prppertyName
         * @return
         */
        public static String toJavaBeanPropertyForSetOrGetMethodName(String propertyName){
                if(!isValidateString(propertyName)){
                        return "";
                }
                propertyName=propertyName.trim();
                if(propertyName.length()<=1){
                        return propertyName.toUpperCase();
                }else{
                        char secondLetter=propertyName.charAt(1);
                        if(secondLetter>='A'&& secondLetter<='Z'){
                                return propertyName;
                        }else{
                                return toUpperCaseFirstLetter(propertyName);
                        }
                }
        }
        /**
         *  The date string into a date object  
         * @param dateString
         * @return
         * @throws ParseException
         */
        public static Date toStringForDate(String dateString) throws Exception{
                Date date=null;
                if(!isValidateString(dateString)){
                        throw new Exception(" Non-date format strings  ");
                }
                dateString=dateString.trim();
                DateFormat format=DateFormat.getDateInstance();
                
                try {
                        date=format.parse(dateString);
                } catch (ParseException e) {
                        throw e;
                }
                return date;
        }
        /**
         *  Verify that the string is entirely composed of numbers and the decimal point  
         *  This method is also not able to verify the hex and octal data  
         * @param number
         * @return
         */
        public static boolean isNumberString(String number){
                
                if(!isValidateString(number)){
                        return false;
                }
                number=number.trim();
                char[] nums=number.toCharArray();
                for(int i=0;i<nums.length;i++){
                        if((nums[i]>='0'&& nums[i]<='9')||(nums[i]=='.')){
                                continue;
                        }else{
                                return false;
                        }
                }
                return true;
        }
        /**
         *  Verify that the string is not entirely digital composition  
         * @param number
         * @return
         */
        public static boolean isCompleteNumberString(String number){
                
                if(!isValidateString(number)){
                        return false;
                }
                number=number.trim();
                char[] nums=number.toCharArray();
                for(int i=0;i<nums.length;i++){
                        if((nums[i]<'0'|| nums[i]>'9')){
                                return false;
                        }
                }
                return true;
        }
        /**
         *  Verify that the date format string and a specified style to match  
         * @param date 
         * @param style  Specifies the style  
         * @return
         * @throws Exception
         */
        public static boolean isValidateDateString(String dateStr,String style) throws Exception{
                if(!isValidateString(style)){
                        return false;
                }
                if(!isValidateString(dateStr)){
                        return false;
                }
                Date date=null;
                try{
                SimpleDateFormat sdf=new SimpleDateFormat(style);
                date =sdf.parse(dateStr);
                }catch(Exception e){
                        throw e;
                }
                if(date==null){
                        return false;
                }
                return true;
        }
        /**
         *  The test method  
         * @param args
         * @throws Exception 
         */
        public static void main(String args[]) throws Exception{
//              System.out.println(StringUtil.toJavaBeanPropertyForSetOrGetMethodName("aBc"));
                if(StringUtil.isValidateDateString("19860912","yyyyMMdd")){
                        System.out.println("yes");
                }else{
                        System.out.println("no");
                }
        }
}
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of The legitimacy of the new and old ID card verification and validation algorithm

  • gddx development experience

    1: System test username and password, it is best not to set difficult to identify the modes: such as 111,111, most likely do not know some are 1. 2: System design, as far as possible the corresponding functional block separate to facilitate other pro ...

  • Struts multi-module design

    Struts version 1.1 after the introduction of the module (Module) concept, to overcome the parallel development of the 1.0 problems. However, the planning template, they are too much trouble, if inadvertently, may be just the opposite, the impact of y ...

  • Unit testing tool JUnit 4

    Reproduced to http://javaee.dahe.cn/bbs/frame.php?frameon=yes&referer=http% 3A / / javaee.dahe.cn / bbs / index.php Unit testing tool JUnit 4 JUnit best practices You intend to put the code on unit testing, what places? Put it and test code mixed toge

  • hibernate study of the thirteenth chapter

    load method and principle analysis of lazy loading The purpose of lazy loading, to reduce unnecessary database queries and enhance performance. Mapping components to use in front of the user category, the Writing test code to do to change: public class Ma

  • TDD == BDD correct

    BDD group where someone filed such a word is not very concerned about it before, perhaps to know that feeling with a mean almost TDD. Today's special look to find some article, which has articles of IBM: http://www.ibm.com/developerworks/cn/java/ ...

  • SipUtils: visit Ali SIP software platform (Service Integration Platform) is a third-party tool Ruby

    SipUtils? Is a helper, for agile accessing the api @ AliSoft? SIP (Services Integration Platform) SipUtils? Is a visit to Ali SIP software platform (Service Integration Platform) is a third-party Ruby libraries, it can be very convenient and quick to ...

  • Ruby 1.9 / Ruby 1.8 =?

    See this from the MSN signature, easy test lost its patience, the result is indeed very exciting. Download Ruby 1.9.1 rc1 Published Address: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/323668 Download address: ftp://ftp.ruby-lang.org/pub/r

  • AJAX Packaging Tools

    Writing a javascript procedure ajax package put in a js file for your reference, please exhibitions. First statement of a few variables: Create XmlHttpRequest object: Implementation of Get / Post requests in the incoming Ways: Get the request method: ...

  • Study Application hibernate (1)

    Basic configurations: Environment: myeclipse Version: 5.5.1 tomcat version: 5.5 1, myEclipse to adjust to the MyEclipse Database Explorer mode; a new database connection, the need for database-driven 2, myEclipse to adjust to the MyEclipse Hibernate ...

  • JUnit Unit Testing Summary

    Read some of the unit test article, from the article in the interception of a number of information, which could be considered in the learning process, a summary of it! See future! Unit testing code is not used to prove you are right, but in order to ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries