1、號碼的結構
公民身份號碼是特徵組合碼,由十七位數字本體碼和一位校驗碼組成。排列順序從左至右依次爲:六位數字地址碼, 八位數字出生日期碼,三位數字順序碼和一位數字校驗 碼。
2、地址碼(前六位數)
表示編碼對象常住戶口所在縣(市、旗、區)的行政區劃代碼,按GB/T2260的規定執行。
3、出生日期碼(第七位至十四位)
表示編碼對象出生的年、月、日,按GB/T7408的規定執行,年、月、日代碼之間不用分隔符。
4、順序碼(第十五位至十七位)
表示在同一地址碼所標識的區域範圍內,對同年、同月、同日出生的人編定的順序號, 順序碼的奇數分配給男性,偶數分配給女性。
5、校驗碼(第十八位數)
(1)十七位數字本體碼加權求和公式 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
(2)計算模 Y = mod(S, 11)
(3)通過模得到對應的校驗碼 Y: 0 1 2 3 4 5 6 7 8 9 10 校驗碼: 1 0 X 9 8 7 6 5 4 3 2
public class IdentityTest {
private static final String IDENTITY_NO_REGEX = "([\\d]{15})|([\\d]{17}+(\\d|[xX]))";
private static final String DATE_REGEX = "((19\\d{2})|(200[0-9])|(201[0-3]))+" +
"((0[1-9])|(1[0-2]))+((0[1-9])|(1[0-9])|(2[0-9])|(3[01]))";
private static char[] VALIDATE_CODE_ARR = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
private static int[] POWSER_ARR = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
public static boolean validate(String identityNo) {
if (identityNo == null)
{
return false;
}
if (!identityNo.matches(IDENTITY_NO_REGEX))
{
return false;
}
String date = identityNo.length() == 15 ? "19" + identityNo.substring(6, 12) : identityNo.substring(6, 14);
System.out.println(date);
if (!date.matches(DATE_REGEX))
{
return false;
}
if (identityNo.length() == 15)
{
return true;
}
int checksum = 0;
for (int i = 0; i < 17; i++)
{
checksum = checksum + (identityNo.charAt(i) - 48) * POWSER_ARR[i];
}
char verifyCode = VALIDATE_CODE_ARR[checksum % 11];
if (identityNo.charAt(17) != verifyCode)
{
return verifyCode == 'X' ? identityNo.charAt(17) == 'x' : false;
}
return true;
}
}