Javaは身分証明書アルゴリズムの検証を実現する


それぞれの身分証明書番号は、むやみにランダムに生成されるのではなく、国の規定に従って、規則的に生成されるので、具体的な規則はここをクリックして見てください.私たちはユーザーの身分証明書の入力を検証して、簡単な桁数の判断だけで、正則検査はテストの要求に達しないので、国家の規定に基づいて、身分証明書の生成規則をアルゴリズムに変えて、アルゴリズムを通じてユーザーの入力が合法かどうかを検証する必要があります:もし合法であれば、ユーザー情報を関連部門に提出して真実性の検証を行います.
次のくだらないことは言わないで、直接道具類に行きます.私のプロジェクトはAndroidプロジェクトなので、Log出力を使いました.もしあなたのプロジェクトがJavaプロジェクトであれば、LogをSystemに変えます.out.println()でいいです.
package com.younghong.utils;

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

import android.util.Log;


/**
 * ClassName: CheckIDCardRule
 *
 * @author younghong
 * @Description:      ,               ,             
 *        :6     +8   +3    +1    
 * @since JDK 1.6
 */

public class CheckIDCardRule {
    /**
     *               
     */
    private static final String BIRTH_DATE_FORMAT = "yyyyMMdd";
    /**
     *           ,1900 1 1 
     */
    private static final Date MIN_BIRTH_DATE = new Date(-2209017600000L);
    /**
     *          
     */
    private static final int NEW_CARD_NUMBER_LENGTH = 18;
    /**
     *          
     */
    private static final int OLD_CARD_NUMBER_LENGTH = 15;
    /**
     * 18            
     */
    private static final char[] VERIFY_CODE = {'1', '0', 'X', '9', '8', '7',
            '6', '5', '4', '3', '2'};
    /**
     * 18     ,              
     */
    private static final int[] VERIFY_CODE_WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1,
            6, 3, 7, 9, 10, 5, 8, 4, 2};
    /**
     *         
     */
    private final String cardNumber;
    /**
     *          ,                
     */
    private Boolean cacheValidateResult = null;
    /**
     *       ,               
     */
    private Date cacheBirthDate = null;
    /**
     *     
     */
    private Date currentDate = new Date();

    public CheckIDCardRule(String cardNumber, String serTime) {

        if (null != cardNumber) {
            cardNumber = cardNumber.trim();
            if (OLD_CARD_NUMBER_LENGTH == cardNumber.length()) {
                //    15      ,      18 
                cardNumber = contertToNewCardNumber(cardNumber);
            }
        }
        if (null != serTime) {
            currentDate = strToDate(serTime, "yyyyMMddhhmmss");
        }
        this.cardNumber = cardNumber;
    }

    /**
     * @return boolean
     * @Title: validate
     * @Description:        
     * @author
     */
    public boolean validate() {
        if (null == this.cacheValidateResult) {
            boolean result = true;
            try {
                //          
                result = result && (null != this.cardNumber);
                //        18(  )
                result = result
                        && NEW_CARD_NUMBER_LENGTH == this.cardNumber.length();
                char ch;
                //       17         
                for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
                    ch = cardNumber.charAt(i);
                    result = result && ch >= '0' && ch <= '9';
                }
                //       18     
                result = result
                        && (calculateVerifyCode(cardNumber) == cardNumber
                        .charAt(NEW_CARD_NUMBER_LENGTH - 1));
                //             ,      1900 
                Date birthDate = getBirthDate();
                result = result && null != birthDate;
                result = result && birthDate.before(currentDate);
                result = result && birthDate.after(MIN_BIRTH_DATE);

                String birthdayPart = getBirthDayPart();
                String realBirthdayPart = this.createBirthDateParser().format(
                        birthDate);
                result = result && (birthdayPart.equals(realBirthdayPart));
            } catch (Exception e) {
                Log.e("      :validate()", e.toString());
                result = false;
            }
            //                 
            cacheValidateResult = Boolean.valueOf(result);
        }
        return cacheValidateResult;
    }

    /**
     *   :      
     *
     * @return Hashtable   
     */
    private static Hashtable GetAreaCode() {
        Hashtable hashtable = new Hashtable();
        hashtable.put("11", "  ");
        hashtable.put("12", "  ");
        hashtable.put("13", "  ");
        hashtable.put("14", "  ");
        hashtable.put("15", "   ");
        hashtable.put("21", "  ");
        hashtable.put("22", "  ");
        hashtable.put("23", "   ");
        hashtable.put("31", "  ");
        hashtable.put("32", "  ");
        hashtable.put("33", "  ");
        hashtable.put("34", "  ");
        hashtable.put("35", "  ");
        hashtable.put("36", "  ");
        hashtable.put("37", "  ");
        hashtable.put("41", "  ");
        hashtable.put("42", "  ");
        hashtable.put("43", "  ");
        hashtable.put("44", "  ");
        hashtable.put("45", "  ");
        hashtable.put("46", "  ");
        hashtable.put("50", "  ");
        hashtable.put("51", "  ");
        hashtable.put("52", "  ");
        hashtable.put("53", "  ");
        hashtable.put("54", "  ");
        hashtable.put("61", "  ");
        hashtable.put("62", "  ");
        hashtable.put("63", "  ");
        hashtable.put("64", "  ");
        hashtable.put("65", "  ");
        hashtable.put("71", "  ");
        hashtable.put("81", "  ");
        hashtable.put("82", "  ");
        hashtable.put("91", "  ");
        return hashtable;
    }

    /**
     * @return String
     * @Title: getAddressCode
     * @Description:              
     * @author
     */
    public String getAddressCode() {
        checkIfValid();
        Hashtable h = GetAreaCode();
        if (h.get(cardNumber.substring(0, 2)) == null) {
            throw new RuntimeException("        !");
        }
        // return this.cardNumber.substring(0, 6);
        return h.get(cardNumber.substring(0, 2));
    }

    /**
     * @return java.util.Date
     * @Title: getBirthDate
     * @Description:            
     * @author
     */
    public Date getBirthDate() {

        if (null == this.cacheBirthDate) {
            try {
                this.cacheBirthDate = createBirthDateParser().parse(
                        getBirthDayPart());
            } catch (ParseException e) {
                Log.e("      !", e.toString());
            } catch (Exception e) {
                Log.e("      !", e.toString());
            }
        }
        return new Date(this.cacheBirthDate.getTime());
    }

    /**
     * @return boolean
     * @Title: isMale
     * @Description:        
     * @author
     */
    public boolean isMale() {
        return 1 == getGenderCode();
    }

    /**
     * @return boolean
     * @Title: isMale
     * @Description:        
     * @author
     */
    public boolean isFemal() {
        return false == isMale();
    }

    /**
     * @return int
     * @Title: getGenderCode
     * @Description:        17 ,     ,     
     * @author
     */
    private int getGenderCode() {
        checkIfValid();
        char genderCode = this.cardNumber.charAt(NEW_CARD_NUMBER_LENGTH - 2);
        return (((int) (genderCode - '0')) & 0x1);
    }

    private String getBirthDayPart() {
        return this.cardNumber.substring(6, 14);
    }

    private SimpleDateFormat createBirthDateParser() {
        return new SimpleDateFormat(BIRTH_DATE_FORMAT);
    }

    private void checkIfValid() {
        if (false == validate()) {
            throw new RuntimeException("        !");
        }
    }

    /**
     * @param cardNumber
     * @return char
     * @Title: calculateVerifyCode
     * @Description:    (     )
     *                S = Sum(Ai * Wi), i = 0...16 ,   17       
     * Ai:   i            
     * Wi:   i         Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
     *     Y = mod(S, 11)
     *             Y: 0 1 2 3 4 5 6 7 8 9 10    : 1 0 X 9 8 7 6 5 4 3 2
     */
    private static char calculateVerifyCode(CharSequence cardNumber) {

        int sum = 0;

        char ch;

        for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
            ch = cardNumber.charAt(i);
            sum += ((int) (ch - '0')) * VERIFY_CODE_WEIGHT[i];
        }
        return VERIFY_CODE[sum % 11];
    }

    /**
     * @param oldCardNumber 15      
     * @Title: contertToNewCardNumber
     * @Description:  15         18      
     * @return:
     */
    private static String contertToNewCardNumber(String oldCardNumber) {
          /*
           * 15       18          :
           * 1: 15       ,"    "   2 ,       "19",  20  ;
           * 2: 15            。18     ,        17   
           */
        StringBuilder buf = new StringBuilder(NEW_CARD_NUMBER_LENGTH);
        buf.append(oldCardNumber.substring(0, 6));
        buf.append("19");
        buf.append(oldCardNumber.substring(6));
        buf.append(CheckIDCardRule.calculateVerifyCode(buf));
        return buf.toString();
    }

    /**
     * @return the cardNumber
     */
    public String getCardNumber() {
        return cardNumber;
    }


    /**
     * String       
     *
     * @param str
     * @return
     */
    public static Date strToDate(String str, String patten) {
        if (str != null) {
            if (patten == null)
                patten = "yyyy-MM-dd";
            SimpleDateFormat formatter = new SimpleDateFormat(patten);
            try {
                Date dt = null;
                dt = formatter.parse(str);
                return dt;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

使用方法も簡単です.以下のようにコードをカプセル化し、検証が必要な場所でこの方法を使用すればいいです.
/**
* @param content          
* @param serTime     ,   yyyy-MM-dd,               。  null,        
* @return       true,     false
*/
private static boolean checkIDCard(String content, String serTime) {
    CheckIDCardRule regex = new CheckIDCardRule(content, serTime);
    return regex.validate();
}