1. 程式人生 > >身份證號碼驗證處理工具類

身份證號碼驗證處理工具類

package com.zotech.basic.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 身份證驗證工具類
 * wulin
 */
public class IdcardUtils {

    /**
     * 中國公民身份證號碼最小長度。
     */
    public static final int CHINA_ID_MIN_LENGTH = 15;

    /**
     * 中國公民身份證號碼最大長度。
     */
    public static final int CHINA_ID_MAX_LENGTH = 18;

    /**
     * 省、直轄市程式碼表
     */
    public static final 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"};

    /**
     * 每位加權因子
     */
    public static final int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9,
            10, 5, 8, 4, 2};

    /**
     * 第18位校檢碼
     */
    public static final String verifyCode[] = {"1", "0", "X", "9", "8", "7",
            "6", "5", "4", "3", "2"};
    /**
     * 最低年限
     */
    public static final int MIN = 1930;
    public static Map cityCodes = new HashMap();
    /**
     * 臺灣身份首字母對應數字
     */
    public static Map twFirstCode = new HashMap();
    /**
     * 香港身份首字母對應數字
     */
    public static Map hkFirstCode = new HashMap();

    static {
        cityCodes.put("11", "北京");
        cityCodes.put("12", "天津");
        cityCodes.put("13", "河北");
        cityCodes.put("14", "山西");
        cityCodes.put("15", "內蒙古");
        cityCodes.put("21", "遼寧");
        cityCodes.put("22", "吉林");
        cityCodes.put("23", "黑龍江");
        cityCodes.put("31", "上海");
        cityCodes.put("32", "江蘇");
        cityCodes.put("33", "浙江");
        cityCodes.put("34", "安徽");
        cityCodes.put("35", "福建");
        cityCodes.put("36", "江西");
        cityCodes.put("37", "山東");
        cityCodes.put("41", "河南");
        cityCodes.put("42", "湖北");
        cityCodes.put("43", "湖南");
        cityCodes.put("44", "廣東");
        cityCodes.put("45", "廣西");
        cityCodes.put("46", "海南");
        cityCodes.put("50", "重慶");
        cityCodes.put("51", "四川");
        cityCodes.put("52", "貴州");
        cityCodes.put("53", "雲南");
        cityCodes.put("54", "西藏");
        cityCodes.put("61", "陝西");
        cityCodes.put("62", "甘肅");
        cityCodes.put("63", "青海");
        cityCodes.put("64", "寧夏");
        cityCodes.put("65", "新疆");
        cityCodes.put("71", "臺灣");
        cityCodes.put("81", "香港");
        cityCodes.put("82", "澳門");
        cityCodes.put("91", "國外");
        twFirstCode.put("A", 10);
        twFirstCode.put("B", 11);
        twFirstCode.put("C", 12);
        twFirstCode.put("D", 13);
        twFirstCode.put("E", 14);
        twFirstCode.put("F", 15);
        twFirstCode.put("G", 16);
        twFirstCode.put("H", 17);
        twFirstCode.put("J", 18);
        twFirstCode.put("K", 19);
        twFirstCode.put("L", 20);
        twFirstCode.put("M", 21);
        twFirstCode.put("N", 22);
        twFirstCode.put("P", 23);
        twFirstCode.put("Q", 24);
        twFirstCode.put("R", 25);
        twFirstCode.put("S", 26);
        twFirstCode.put("T", 27);
        twFirstCode.put("U", 28);
        twFirstCode.put("V", 29);
        twFirstCode.put("X", 30);
        twFirstCode.put("Y", 31);
        twFirstCode.put("W", 32);
        twFirstCode.put("Z", 33);
        twFirstCode.put("I", 34);
        twFirstCode.put("O", 35);
        hkFirstCode.put("A", 1);
        hkFirstCode.put("B", 2);
        hkFirstCode.put("C", 3);
        hkFirstCode.put("R", 18);
        hkFirstCode.put("U", 21);
        hkFirstCode.put("Z", 26);
        hkFirstCode.put("X", 24);
        hkFirstCode.put("W", 23);
        hkFirstCode.put("O", 15);
        hkFirstCode.put("N", 14);
    }

    /**
     * 將15位身份證號碼轉換為18位
     *
     * @param idCard 15位身份編碼
     * @return 18位身份編碼
     */
    public static String conver15CardTo18(String idCard) {
        String idCard18 = "";
        if (idCard.length() != CHINA_ID_MIN_LENGTH) {
            return null;
        }
        if (isNum(idCard)) {
            // 獲取出生年月日
            String birthday = idCard.substring(6, 12);
            Date birthDate = null;
            try {
                birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            if (birthDate != null)
                cal.setTime(birthDate);
            // 獲取出生年(完全表現形式,如:2010)
            String sYear = String.valueOf(cal.get(Calendar.YEAR));
            idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8);
            // 轉換字元陣列
            char[] cArr = idCard18.toCharArray();
            if (cArr != null) {
                int[] iCard = converCharToInt(cArr);
                int iSum17 = getPowerSum(iCard);
                // 獲取校驗位
                String sVal = getCheckCode18(iSum17);
                if (sVal.length() > 0) {
                    idCard18 += sVal;
                } else {
                    return null;
                }
            }
        } else {
            return null;
        }
        return idCard18;
    }

    /**
     * 驗證身份證是否合法
     */
    @Deprecated
    public static boolean validateCard(String idCard) {
        String card = idCard.trim();
        if (validateIdCard18(card)) {
            return true;
        }
        if (validateIdCard15(card)) {
            return true;
        }
        String[] cardval = validateIdCard10(card);
        if (cardval != null) {
            if (cardval[2].equals("true")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 驗證18位身份編碼是否合法
     *
     * @param idCard 身份編碼
     * @return 是否合法
     */
    public static boolean validateIdCard18(String idCard) {
        boolean bTrue = false;
        if (idCard.length() == CHINA_ID_MAX_LENGTH) {
            // 前17位
            String code17 = idCard.substring(0, 17);
            // 第18位
            String code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH);
            if (isNum(code17)) {
                char[] cArr = code17.toCharArray();
                if (cArr != null) {
                    int[] iCard = converCharToInt(cArr);
                    int iSum17 = getPowerSum(iCard);
                    // 獲取校驗位
                    String val = getCheckCode18(iSum17);
                    if (val.length() > 0) {
                        if (val.equalsIgnoreCase(code18)) {
                            bTrue = true;
                        }
                    }
                }
            }
        }
        return bTrue;
    }

    /**
     * 驗證15位身份編碼是否合法
     *
     * @param idCard 身份編碼
     * @return 是否合法
     */
    public static boolean validateIdCard15(String idCard) {
        if (idCard.length() != CHINA_ID_MIN_LENGTH) {
            return false;
        }
        if (isNum(idCard)) {
            String proCode = idCard.substring(0, 2);
            if (cityCodes.get(proCode) == null) {
                return false;
            }
            String birthCode = idCard.substring(6, 12);
            Date birthDate = null;
            try {
                birthDate = new SimpleDateFormat("yy").parse(birthCode
                        .substring(0, 2));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            if (birthDate != null)
                cal.setTime(birthDate);
            if (!valiDate(cal.get(Calendar.YEAR),
                    Integer.valueOf(birthCode.substring(2, 4)),
                    Integer.valueOf(birthCode.substring(4, 6)))) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 驗證10位身份編碼是否合法
     *
     * @param idCard 身份編碼
     * @return 身份證資訊陣列
     * 

* [0] - 臺灣、澳門、香港 [1] - 性別(男M,女F,未知N) [2] - 是否合法(合法true,不合法false) * 若不是身份證件號碼則返回null *

*/ public static String[] validateIdCard10(String idCard) { String[] info = new String[3]; String card = idCard.replaceAll("[\\(|\\)]", ""); if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) { return null; } if (idCard.matches("^[a-zA-Z][0-9]{9}$")) { // 臺灣 info[0] = "臺灣"; System.out.println("11111"); String char2 = idCard.substring(1, 2); if (char2.equals("1")) { info[1] = "M"; System.out.println("MMMMMMM"); } else if (char2.equals("2")) { info[1] = "F"; System.out.println("FFFFFFF"); } else { info[1] = "N"; info[2] = "false"; System.out.println("NNNN"); return info; } info[2] = validateTWCard(idCard) ? "true" : "false"; } else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳門 info[0] = "澳門"; info[1] = "N"; } else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港 info[0] = "香港"; info[1] = "N"; info[2] = validateHKCard(idCard) ? "true" : "false"; } else { return null; } return info; } /** * 驗證臺灣身份證號碼 * * @param idCard 身份證號碼 * @return 驗證碼是否符合 */ public static boolean validateTWCard(String idCard) { String start = idCard.substring(0, 1); String mid = idCard.substring(1, 9); String end = idCard.substring(9, 10); Integer iStart = twFirstCode.get(start); Integer sum = iStart / 10 + (iStart % 10) * 9; char[] chars = mid.toCharArray(); Integer iflag = 8; for (char c : chars) { sum = sum + Integer.valueOf(c + "") * iflag; iflag--; } return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false; } /** * 驗證香港身份證號碼(存在Bug,部份特殊身份證無法檢查) *

* 身份證前2位為英文字元,如果只出現一個英文字元則表示第一位是空格,對應數字58 前2位英文字元A-Z分別對應數字10-35 * 最後一位校驗碼為0-9的數字加上字元"A","A"代表10 *

*

* 將身份證號碼全部轉換為數字,分別對應乘9-1相加的總和,整除11則證件號碼有效 *

* * @param idCard 身份證號碼 * @return 驗證碼是否符合 */ public static boolean validateHKCard(String idCard) { String card = idCard.replaceAll("[\\(|\\)]", ""); Integer sum = 0; if (card.length() == 9) { sum = (Integer.valueOf(card.substring(0, 1).toUpperCase() .toCharArray()[0]) - 55) * 9 + (Integer.valueOf(card.substring(1, 2).toUpperCase() .toCharArray()[0]) - 55) * 8; card = card.substring(1, 9); } else { sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase() .toCharArray()[0]) - 55) * 8; } String mid = card.substring(1, 7); String end = card.substring(7, 8); char[] chars = mid.toCharArray(); Integer iflag = 7; for (char c : chars) { sum = sum + Integer.valueOf(c + "") * iflag; iflag--; } if (end.toUpperCase().equals("A")) { sum = sum + 10; } else { sum = sum + Integer.valueOf(end); } return (sum % 11 == 0) ? true : false; } /** * 將字元陣列轉換成數字陣列 * * @param ca 字元陣列 * @return 數字陣列 */ public static int[] converCharToInt(char[] ca) { int len = ca.length; int[] iArr = new int[len]; try { for (int i = 0; i < len; i++) { iArr[i] = Integer.parseInt(String.valueOf(ca[i])); } } catch (NumberFormatException e) { e.printStackTrace(); } return iArr; } /** * 將身份證的每位和對應位的加權因子相乘之後,再得到和值 * * @param iArr * @return 身份證編碼。 */ public static int getPowerSum(int[] iArr) { int iSum = 0; if (power.length == iArr.length) { for (int i = 0; i < iArr.length; i++) { for (int j = 0; j < power.length; j++) { if (i == j) { iSum = iSum + iArr[i] * power[j]; } } } } return iSum; } /** * 將power和值與11取模獲得餘數進行校驗碼判斷 * * @param iSum * @return 校驗位 */ public static String getCheckCode18(int iSum) { String sCode = ""; switch (iSum % 11) { case 10: sCode = "2"; break; case 9: sCode = "3"; break; case 8: sCode = "4"; break; case 7: sCode = "5"; break; case 6: sCode = "6"; break; case 5: sCode = "7"; break; case 4: sCode = "8"; break; case 3: sCode = "9"; break; case 2: sCode = "x"; break; case 1: sCode = "0"; break; case 0: sCode = "1"; break; } return sCode; } /** * 根據身份編號獲取年齡 * * @param idCard 身份編號 * @return 年齡 */ public static int getAgeByIdCard(String idCard) { int iAge = 0; if (idCard.length() == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } String year = idCard.substring(6, 10); Calendar cal = Calendar.getInstance(); int iCurrYear = cal.get(Calendar.YEAR); iAge = iCurrYear - Integer.valueOf(year); return iAge < 0 ? 0 : iAge; } /** * 根據身份編號獲取生日 * * @param idCard 身份編號 * @return 生日(yyyyMMdd) */ public static String getBirthByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return idCard.substring(6, 14); } /** * 根據身份編號獲取生日年 * * @param idCard 身份編號 * @return 生日(yyyy) */ public static Short getYearByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(6, 10)); } /** * 根據身份編號獲取生日月 * * @param idCard 身份編號 * @return 生日(MM) */ public static Short getMonthByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(10, 12)); } /** * 根據身份編號獲取生日天 * * @param idCard 身份編號 * @return 生日(dd) */ public static Short getDateByIdCard(String idCard) { Integer len = idCard.length(); if (len < CHINA_ID_MIN_LENGTH) { return null; } else if (len == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } return Short.valueOf(idCard.substring(12, 14)); } /** * 根據身份編號獲取性別 * * @param idCard 身份編號 * @return 性別(M-男,F-女,N-未知) */ public static String getGenderByIdCard(String idCard) { String sGender = "0"; if (idCard.length() == CHINA_ID_MIN_LENGTH) { idCard = conver15CardTo18(idCard); } String sCardNum = idCard.substring(16, 17); if (Integer.parseInt(sCardNum) % 2 != 0) { sGender = "1"; } else { sGender = "2"; } return sGender; } /** * 根據身份編號獲取戶籍省份 * * @param idCard 身份編碼 * @return 省級編碼。 */ public static String getProvinceByIdCard(String idCard) { int len = idCard.length(); String sProvince = null; String sProvinNum = ""; if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) { sProvinNum = idCard.substring(0, 2); } sProvince = cityCodes.get(sProvinNum); return sProvince; } /** * 數字驗證 * * @param val * @return 提取的數字。 */ public static boolean isNum(String val) { return val == null || "".equals(val) ? false : val.matches("^[0-9]*$"); } /** * 驗證小於當前日期 是否有效 * * @param iYear 待驗證日期(年) * @param iMonth 待驗證日期(月 1-12) * @param iDate 待驗證日期(日) * @return 是否有效 */ public static boolean valiDate(int iYear, int iMonth, int iDate) { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int datePerMonth; if (iYear < MIN || iYear >= year) { return false; } if (iMonth < 1 || iMonth > 12) { return false; } switch (iMonth) { case 4: case 6: case 9: case 11: datePerMonth = 30; break; case 2: boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0)) && (iYear > MIN && iYear < year); datePerMonth = dm ? 29 : 28; break; default: datePerMonth = 31; } return (iDate >= 1) && (iDate <= datePerMonth); } /** * 身份證最新驗證 * wulin * @param gets 身份證號碼 * @return */ public static boolean idCardValidate(String gets) { int[] Wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1};// 加權因子; int[] ValideCode = {1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2};// 身份證驗證位值,10代表X; gets=gets.trim().replace(" ",""); String a_idCard[] = gets.split("");// 得到身份證陣列 if (gets.length() == 15) { return isValidityBrithBy15IdCard(gets); } else if (gets.length() == 18) { if (isValidityBrithBy18IdCard(gets) && isTrueValidateCodeBy18IdCard(a_idCard, Wi, ValideCode)) { return true; } return false; } return false; } private static boolean isTrueValidateCodeBy18IdCard(String a_idCard[], int Wi[], int ValideCode[]) { int sum = 0; // 宣告加權求和變數 if (a_idCard[17].toLowerCase().equals("x")) { a_idCard[17] = "10";// 將最後位為x的驗證碼替換為10方便後續操作 } for (int i = 0; i < 17; i++) { sum += Wi[i] * Integer.parseInt(a_idCard[i]);// 加權求和 } int valCodePosition = sum % 11;// 得到驗證碼所位置 if (a_idCard[17].equals(ValideCode[valCodePosition] + "")) { return true; } return false; } private static boolean isValidityBrithBy15IdCard(String idCard15) { String year = idCard15.substring(6, 8); String month = idCard15.substring(8, 10); String day = idCard15.substring(10, 12); Date temp_date = new Date(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day)); // 對於老身份證中的你年齡則不需考慮千年蟲問題而使用getYear()方法 if (temp_date.getYear() != Integer.parseInt(year) || temp_date.getMonth() != Integer.parseInt(month) - 1 || temp_date.getDate() != Integer.parseInt(day)) { return false; } return true; } private static boolean isValidityBrithBy18IdCard(String idCard18) { String year = idCard18.substring(6, 10); String month = idCard18.substring(10, 12); String day = idCard18.substring(12, 14); Date temp_date = new Date(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day)); // 這裡用getFullYear()獲取年份,避免千年蟲問題 if (temp_date.getYear() != Integer.parseInt(year) || temp_date.getMonth() != Integer.parseInt(month) - 1 || temp_date.getDate() != Integer.parseInt(day)) { return false; } return true; } /** *測試 * @param args */ /*public static void main(String[] args) { Scanner scanner=new Scanner(System.in); for (int i=0;i<10;i++){ System.out.println("輸入身份證"); String name=scanner.nextLine(); System.out.println(idCardValidate(name)); } }*/ }

相關推薦

身份證號碼驗證處理工具

package com.zotech.basic.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 身份證驗證工具類 * wulin */ publ

身份證號碼驗證工具,學習備用

import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; public class IDCardValidate { public static

Java 身份證號碼驗證工具

package cn.hlq.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.ut

【全】JAVA 身份證號碼驗證工具(省份、性別、生肖、星座)

package com.stt; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; i

身份證驗證java工具(糾正網上流行程式碼錯誤)

參考網上程式碼,不過網上程式碼全部是拷貝的,糾正下,身份證前2位代表地區,64是青海,65是新疆。。。以下程式碼已糾正並測試 /** * 身份證驗證的工具(支援5位或18位省份證) 身份證號碼結構: 17位數字和1位校驗碼:6位地址碼數字,8位生日數字,

android ImageUtils 圖片處理工具

copy pac float can turn getconf ble static ring /** * 加入文字到圖片。相似水印文字。 * @param gContext * @param gResId * @param gText * @re

編程樂趣:身份證號碼驗證的方法

adl substring track content else if ont article name out 隨著如今互聯網的發展,越來越多的註冊用戶的地方都用到了身份證。那麽對於輸入的身份證怎樣驗證呢?看以下的代碼,事實上非常easy。主要註意的是,眼下的身份證分

時間處理工具

nim mount minute int quest lac asn ren 問題 import java.sql.Timestamp;import java.text.ParseException;import java.text.SimpleDateFormat;i

javascript身份證號碼驗證

返回 markdown user 問題 spa div mod 偶數 efi https://github.com/oxcow/id-number-validator 版權聲明: 關於《javascript身份證號碼驗證》的一切權利歸作者@Leeyee所有;

Java實現身份證號碼驗證源碼分享

分隔 toc bst nbsp port birt random exti 一位數 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar;

15/18位身份證號碼驗證的正則表達式總結(詳細版)

校驗碼 輸入 詳細 wid width adding 方式 http 效率 前言 開發過程中,常常需要對一些輸入信息進行有效性驗證,使用正則表達式進行校驗是最簡單、效率最高的方式了,下面就來看看15/18位身份證號碼驗證的正則表達式吧。 介紹 xxxxxx yyyy MM

Java 身份證號碼驗證

str 河北 有效 sys system day pub 位或 序號 身份證號碼驗證   1、號碼的結構 公民身份號碼是特征組合碼,由十七位數字本體碼和一位校驗碼組成。排列順序從左至右依次為:六位數字地址碼,八位數字出生日期碼,三位數字順序碼和一位數字校驗碼   

生成4位隨機驗證工具

urn build public har spa java dom 個人 ont keyUtil: package com.duocy.util; import java.util.Random; public class keyUtil {public Str

點選生成動態驗證碼(工具)

1.頁面 <!--驗證碼--> <div class="col-sm-3"> <img id="vcode" src="/checkCode" style="cursor:pointer"> </div>

json處理工具

package com.sys.util; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType

java常用工具(二)—— JSON處理工具

tor ast val simple sta 轉換 local pass password package com.springboot.commons.utils; import com.springboot.commons.scan.JacksonObjectMapp

圖片驗證工具

工具類 /** * Created by qd on 2015/11/12. */ import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage

java後端時間處理工具,返回 "XXX 前" 的字串

我們經常會遇到顯示 "某個之間之前" 的需求(比如各種社交軟體,在回覆訊息時,顯示xxx之前回復),我們可以在後端進行處理,也可以在前端進行處理,這裡講講在後端進行處理的方法. 其實很簡單,我們只需要將從資料庫中取到的date型別的欄位進行處理。 工具類如下: import java.

工作日處理工具(包括工作日判斷和工作日區間判斷)

  對於工作日處理相對來說還是比較簡單的,不外乎就是週末判斷和假期判斷。   不過,有些人會把它們寫死在類裡面,看以下程式碼:   耦合性較強的程式碼:       public class Weekda

圖片處理工具 util

PathUtil package util; public class PathUtil { private static String seperator = System.getProperty("file.separator"); // 獲取根目錄