工具类- 身份证校验

public class IDCardVerify {

	public static void main(String[] args) throws Exception {
		String idcard = "432503198711105699";
		System.out.println(verify(idcard));
	}
	
	/**
	 * 校验身份证校验位是否合法
	 */
	public static Boolean verify(String idcard) throws Exception {

		if (18 != idcard.length()) {
			throw new Exception("身份证长度不是18位,无法校验!");
		}
		//字符串形式身份证转换为整型数组
		int[] iarray = string2intArray(idcard);
		
		// 1、身份证每位上的数字与对应的数字相乘后求和sum
		// 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
		int sum = 0;
		sum += 7  * iarray[0];
		sum += 9  * iarray[1];
		sum += 10 * iarray[2];
		sum += 5  * iarray[3];
		sum += 8  * iarray[4];
		sum += 4  * iarray[5];
		sum += 2  * iarray[6];
		sum += 1  * iarray[7];
		sum += 6  * iarray[8];
		sum += 3  * iarray[9];
		sum += 7  * iarray[10];
		sum += 9  * iarray[11];
		sum += 10 * iarray[12];
		sum += 5  * iarray[13];
		sum += 8  * iarray[14];
		sum += 4  * iarray[15];
		sum += 2  * iarray[16];
        
		//2、sum整除11得余数mod
		int mod = sum % 11;
		String ver = null;

		//3、根据mod获取对应的校验位
		//0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2
		switch (mod) {
		case  0: ver = "1"; break;
		case  1: ver = "0"; break;
		case  2: ver = "x"; break;
		case  3: ver = "9"; break;
		case  4: ver = "8"; break;
		case  5: ver = "7"; break;
		case  6: ver = "6"; break;
		case  7: ver = "5"; break;
		case  8: ver = "4"; break;
		case  9: ver = "3"; break;
		case 10: ver = "2";break;
		default: throw new Exception("计算校验码异常!");
		}

		String ver2 = String.valueOf(iarray[17]);
		if (0 == ver.compareToIgnoreCase(ver2)) {
			return true;
		}

		return false;
	}
	
	/**
	 * 身份证 --> 整型数组
	 */
	public static int[] string2intArray(String str){
		char[] carray = str.toCharArray();
		int[] ints = new int[carray.length];
		for(int i = 0; i< carray.length ; i++){
			ints[i] = Integer.valueOf(String.valueOf(carray[i]));
		}
		return ints;		
	}
}

你可能感兴趣的:(java,身份证,校验)