校验身份证号码

时间:2022-01-26 22:36:24

校验身份证是否正确,必须是二代身份证,身份证号是18位

 /**
* 验证18位身份编码是否合法
*
* @param idCard 身份编码
* @return 是否合法
*/

public static boolean validateIdCard18(String idCard) {
boolean bTrue = false;
if (idCard.length() == 18) {
// 前17位
String code17 = idCard.substring(0, 17);
// 第18位
String code18 = idCard.substring(17, 18);
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;
}
/**
* 数字验证
* @param val
* @return 提取的数字。
*/

public static boolean isNum(String val) {
return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
}
/**
* 将字符数组转换成数字数组
* @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;
}