校驗手機號、身份證、IP地址、密碼強度等常用方法

package cn.ncss.cy.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

public class CommonTool {

	private static final Logger log = LoggerFactory.getLogger(CommonTool.class);

	/**
	 * md5加密
	 * 
	 * @param loginName
	 * @return
	 */
	public final static String md5(String loginName) {
		Md5Hash md5LoginName = new Md5Hash(loginName);
		return md5LoginName.toHex();
	}

	/**
	 * 校驗手機號註冊
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean validateRegisterPhone(String phone, String regionCode) {
		if (!StringUtils.hasText(phone)) {
			return false;
		}
		if ("886".equals(regionCode)) {
			return phone.matches(StaticValue.DEFAULT_TW_PHONE_PATTERN);
		} else if ("852".equals(regionCode)) {
			return phone.matches(StaticValue.DEFAULT_HK_PHONE_PATTERN);
		} else if ("853".equals(regionCode)) {
			return phone.matches(StaticValue.DEFAULT_MO_PHONE_PATTERN);
		} else {
			return phone.matches(StaticValue.DEFAULT_PHONE_PATTERN);
		}

	}

	/**
	 * 校驗手機號
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean validatePhone(String phone) {
		if (!StringUtils.hasText(phone)) {
			return false;
		}
		if (phone.matches(StaticValue.DEFAULT_PHONE_PATTERN) || phone.matches(StaticValue.DEFAULT_TW_PHONE_PATTERN)
				|| phone.matches(StaticValue.DEFAULT_HK_PHONE_PATTERN)
				|| phone.matches(StaticValue.DEFAULT_MO_PHONE_PATTERN)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 校驗密碼強度
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean validatePassword(String password) {
		if (!StringUtils.hasText(password)) {
			return false;
		}
		return password.matches(StaticValue.DEFAULT_PASSWORD_PATTERN);
	}

	/**
	 * 獲取ip地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		if (request == null) {
			return "unknown";
		}
		String ip = request.getHeader("x-forwarded-for");
		log.info(String.format("ip from x-forwarded-for: %s", ip));
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 根據GB 11714-1997標準對組織機構代碼中的校驗位進行校驗
	 * 
	 * @param orgCode
	 *            組織機構代碼
	 * @return 是否正確的組織機構代碼
	 */
	public static boolean checkOrgCode(String orgCode) {
		if (!StringUtils.hasText(orgCode)) {
			return false;
		}
		orgCode = orgCode.replaceAll("-", "");
		orgCode = orgCode.replaceAll("—", "");
		orgCode = orgCode.replaceAll("-", "");
		orgCode = orgCode.replaceAll("-", "");
		if (orgCode.length() != 9 || orgCode.equals("000000000") || orgCode.equals("123456788"))
			return false;
		int chkNum = 0; // 校驗數
		int[] factors = { 3, 7, 9, 10, 5, 8, 4, 2 }; // 加權因子
		// 取組織機構代碼的八位本體代碼爲基數,與相應的加權因子相乘後求和,進行校驗數的計算
		for (int i = 0; i < 8; i++) {
			char ch = orgCode.charAt(i);
			int num = 0;
			// 獲取八位本體代碼並轉換爲相應的數字
			if (ch >= 'A' && ch <= 'Z') {
				num = ch - 'A' + 10;
			} else if (ch >= '0' && ch <= '9') {
				num = ch - '0';
			} else {
				return false; // 含有數字字母以外的字符,直接返回錯誤
			}
			num = num * factors[i]; // 取Wi本體代碼與加權銀子對應各位相乘
			chkNum += num; // 乘積相加求和數
		}
		chkNum = chkNum % 11; // 取模數11除和數,求餘數
		chkNum = 11 - chkNum; // 以模數11減餘數,求校驗碼數值
		if (chkNum == 11) {
			chkNum = 0; // 校驗數爲11時直接轉換爲0
		}

		// 獲取校驗碼,並跟校驗數進行比較。校驗數爲10時候校驗碼應爲“X”
		String chkCode = String.valueOf(orgCode.charAt(8));
		if (chkCode.endsWith(String.valueOf(chkNum)) || (chkCode.equals("X") && chkNum == 10)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 校驗工商行政註冊碼
	 * 
	 * @param number
	 * @return
	 */
	public static boolean checkRegisterNumber(String number) {
		if (number.length() != 15) {
			return false;
		} else if (!isNumeric(number)) {// 判斷是否都是數字
			if (number.endsWith("X") && ("NA".equals(number.substring(6, 8)) || "NB".equals(number.substring(6, 8)))) {
				return true;
			}
			return false;
		}
		// 對於此註冊碼的前六位的校驗即:首次登記機關代碼從工商行政註冊號的編制規則 4.2來看,機關代碼就全是地區代碼,
		// 所以前六位目前暫無理由校驗不合法
		// 最後一位(第十五位)是校驗位
		int checkBit = Integer.parseInt(number.substring(14));
		int num = checkNum(10, number.substring(0, 14));
		if ((checkBit + num) % 10 == 1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 檢測字符傳是否全爲數字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 按照GB/T 17710,MOD 11,10校驗公式 最終遞歸循環得到 P_15 % 11,用於調用處來驗證是否正確
	 * 
	 * @param P_num
	 * @param subStr用來遞歸的子串
	 * @return
	 */
	public static int checkNum(int P_num, String subStr) {
		if ("".equals(subStr)) {// 直到遞歸無剩餘子串,可返回結果
			return P_num % 11;
		}
		int sub_Num = Integer.parseInt(subStr.substring(0, 1));// 每次截取第一位用來處理
		sub_Num = P_num % 11 + sub_Num;
		P_num = (sub_Num % 10 != 0 ? sub_Num % 10 : 10) * 2;
		return checkNum(P_num, subStr.substring(1));// 下一次進入遞歸的內容則是出去第一位的其餘子串
	}

	public static BindingResult validateIdCard(BindingResult bindingResult, String idCardType, String idCard) {
		if (idCardType == null || idCard == null || idCardType.equals("") || idCard.equals("")) {
			bindingResult.rejectValue("idCardType", null, "請選擇正確的證件類型");
			return bindingResult;
		}
		if (idCardType.equals("ML")) {
			if (!CommonTool.validateMLcard(idCard)) {
				bindingResult.rejectValue("idCard", null, "請輸入正確的證件號碼");
				return bindingResult;
			}
		} else if (idCardType.equals("HK")) {
			if (!CommonTool.validateHKCard(idCard)) {
				bindingResult.rejectValue("idCard", null, "請輸入正確的證件號碼");
				return bindingResult;
			}
		} else if (idCardType.equals("MO")) {
			if (!CommonTool.validateMOCard(idCard)) {
				bindingResult.rejectValue("idCard", null, "請輸入正確的證件號碼");
				return bindingResult;
			}
		} else if (idCardType.equals("TW")) {
			if (!CommonTool.validateTWCard(idCard)) {
				bindingResult.rejectValue("idCard", null, "請輸入正確的證件號碼");
				return bindingResult;
			}
		} else if (idCardType.equals("HZ")) {
		} else if (idCardType.equals("QT")) {
		} else {
			bindingResult.rejectValue("idCardType", null, "請輸入正確的證件類型");
			return bindingResult;
		}
		return bindingResult;

	}

	/**
	 * 檢測身份證
	 * 
	 * @param value
	 * @return
	 */
	public static boolean validateMLcard(String value) {
		int[] weight = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
		// 校驗碼
		int[] checkDigit = new int[] { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
		int sum = 0;
		if (value.matches(
				"((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)\\d{4})((((19|20)(([02468][048])|([13579][26]))0229))|((20[0-9][0-9])|(19[0-9][0-9]))((((0[1-9])|(1[0-2]))((0[1-9])|(1\\d)|(2[0-8])))|((((0[1,3-9])|(1[0-2]))(29|30))|(((0[13578])|(1[02]))31))))((\\d{3}(x|X))|(\\d{4}))") == true) {
			// 此循環是先取出身份證號碼一個一個的取出,然後取出加權因子的數 一個一個的取出  最後算出他們的和 
			for (int i = 0; i < 17; i++) {
				int b = Integer.parseInt(value.substring(i, i + 1));// 取出輸入身份證一個一個的號碼 然後轉化爲Integer 
				int a = weight[i];// 取出加權因子的一個一個的數 
				sum = a * b + sum;// 累加求和;
			}
			int mod = sum % 11;
			String idcard = value;
			if (value.contains("x")) {
				idcard = value.replace('x', 'X');
			}
			if (idcard.contains("X")) {
				if (idcard.substring(17, 18).charAt(0) == checkDigit[mod]) {
					return true;
				} else {
					return false;
				}
			} else {

				if (idcard.substring(17, 18).equals(String.valueOf(checkDigit[mod]))) {
					return true;
				} else {
					return false;
				}
			}
		} else {
			return false;
		}
	}

	public static boolean validateHZCard(String idCard) {
		if (idCard == null || idCard.equals("")) {
			return false;
		}
		if (!idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) {
			return false;
		}
		return true;
	}

	public static boolean validateHKCard(String idCard) {
		String card = idCard.replaceAll("[\\(|\\)]", "");
		if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) {
			return false;
		}
		if (!idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) {
			return false;
		}
		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;
	}

	public static boolean validateMOCard(String str) {
		String card = str.replaceAll("[\\(|\\)]", "");
		if (card.length() != 8) {
			return false;
		}
		if (str.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) {
			return true;
		}
		return false;
	}

	public static boolean validateTWCard(String str) {
		String card = str.replaceAll("[\\(|\\)]", "");
		if (card.length() != 10) {
			return false;
		}
		if (str.matches("^[a-zA-Z][0-9]{9}$")) {
			return true;
		}
		return false;
	}

	// 判斷密碼強度
	public static String getLevel(String password) {
		if (password.matches("^\\d+$") || password.matches("^[a-zA-Z]+$")
				|| password.matches("^[-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$")) {
			return "LOW";
		} else if (password.matches("^(?!\\d+$)(?![a-zA-Z]+$)[a-zA-Z\\d]+$")
				|| password.matches(
						"^(?![a-zA-Z]+$)(?![-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$)[a-zA-Z-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$")
				|| password.matches(
						"^(?!\\d+)(?![-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$)[\\d-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$")) {
			return "MIDDLE";
		} else if (password.matches(
				"^(?![a-zA-z]+$)(?!\\d+$)(?![-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$)(?![a-zA-z\\d]+$)(?![a-zA-z-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$)(?![\\d-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$)[a-zA-Z\\d-`=\\;',./~!@#$%^&*()_+|{}:\"<>\\[\\]?]+$")) {
			return "HIGH";
		}
		return "LOW";
	}

	public static String jsonizeCode(String key, Object value) {
		return String.format("\"%s\":\"%s\",", key, value);
	}

	public static String jsonizeDes(String key, Object value) {
		return String.format("\"%s\":\"%s\"", key, value);
	}

	public static HttpServletResponse setHeader(String downloadType, String fileType, String name,
			HttpServletRequest request, HttpServletResponse response) {
		if ("downloadphysical".equals(downloadType) || "attachment".equals(downloadType)) {
			if (fileType.equals(".pdf")) {
				response.setContentType("application/pdf");
			} else if (fileType.equals(".doc")) {
				response.setContentType("application/msword");
			} else {
				response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
			}
		} else if ("downloadpptx".equals(downloadType)) {
			response.setContentType("application/vnd.ms-powerpoint");
		} else if ("downloadvideo".equals(downloadType)) {
			response.setContentType("video/mpeg");
		} else if ("downloadzip".equals(downloadType)) {
			response.setContentType("application/zip");
		}
		String agent = request.getHeader("USER-AGENT");
		String headerFilename = null;
		try {
			if ((agent != null)
					&& (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("Trident") || -1 != agent.indexOf("Edge"))) {

				headerFilename = "attachment;filename=" + URLEncoder.encode(name.replace(",", ",") + fileType, "UTF-8");

			} else {

				headerFilename = "attachment;filename="
						+ new String((name.replace(",", ",") + fileType).getBytes("UTF-8"), "ISO-8859-1");

			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.toString());
		}
		response.setHeader("Content-Disposition", headerFilename);
		return response;
	}

	public static void downFile(File file, HttpServletRequest request, HttpServletResponse response) {
		try (InputStream in = new FileInputStream(file); ServletOutputStream os = response.getOutputStream()) {
			byte[] data = new byte[1024];
			int readed = 0;
			while ((readed = in.read(data)) != -1) {
				os.write(data, 0, readed);
			}
			os.flush();
		} catch (Exception e) {
			log.error(e.toString());
		}
	}

	/**
	 * 驗證頭像
	 * 
	 * @param file
	 * @param bindingResult
	 * @return
	 */
	public static BindingResult validateHeadPortrait(Part file, BindingResult bindingResult) {
		if (file == null || file.getSize() <= 1) {
			bindingResult.rejectValue("fileUri", null, "個人頭像文件不能爲空");
			return bindingResult;
		}
		if (hasSizeError(file)) {
			bindingResult.rejectValue("fileUri", null, "個人頭像文件大小不符合要求");
			return bindingResult;
		}
		String fileName = file.getSubmittedFileName().toLowerCase();
		String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
		if (hasImageFormatError(fileSuffix)) {
			bindingResult.rejectValue("fileUri", null, "個人頭像文件格式不符合要求");
			return bindingResult;
		}
		return bindingResult;
	}

	/**
	 * 驗證文件大小
	 * 
	 * @param file
	 * @return
	 */
	public static boolean hasSizeError(Part file) {
		if (file.getSize() > StaticValue.TALENT_HEAD_PORTRAIT_MAX_SIZE) {
			return true;
		}
		return false;
	}

	/**
	 * 驗證格式
	 * 
	 * @param file
	 * @return
	 */
	public static boolean hasImageFormatError(String fileSuffix) {
		if (fileSuffix.equalsIgnoreCase(".jpg") || fileSuffix.equalsIgnoreCase(".jpeg")
				|| fileSuffix.equalsIgnoreCase(".png") || fileSuffix.equalsIgnoreCase(".gif")) {
			return false;
		}
		return true;
	}

	/**
	 * 驗證名片文件大小
	 * 
	 * @param file
	 * @return
	 */
	public static boolean hasSizeErrorCard(Part file) {
		if (file.getSize() > StaticValue.CARD_MAX_SIZE) {
			return true;
		}
		return false;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章