bank card verification

bank card verification

 

 

 

public class CheckBankCard {
	/*
	 * Verification process:
	 * 1. Starting from the last digit of the card number, add the odd digits (1, 3, 5, etc.) in reverse.
	 * 2. Starting from the last digit of the card number, reversely multiply the even-digit number by 2 (if the product is two digits, add the ten-digit one-digit number, that is, subtract 9 from it), and then sum up.
	 * 3. Add the sum of odd digits to the sum of even digits, and the result should be divisible by 10.
	 */
	/**
	 * Verify bank card number
	 */
	public static boolean checkBankCard(String bankCard) {
		if (bankCard.length() < 15 || bankCard.length() > 19) {
			return false;
		}
		char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
		if (bit == 'N') {
			return false;
		}
		return bankCard.charAt(bankCard.length() - 1) == bit;
	}

	/**
	 * Use Luhm check algorithm to obtain check digit from bank card number without check digit
	 *
	 * @param nonCheckCodeBankCard
	 * @return
	 */
	public static char getBankCardCheckCode(String nonCheckCodeBankCard) {
		if (nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0 || !nonCheckCodeBankCard.matches("\\d+")) {
			// If the data is not passed, return N
			return 'N';
		}
		char[] chs = nonCheckCodeBankCard.trim().toCharArray();
		int luhmSum = 0;
		for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if (j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
	}

	public static void main(String[] args) {
		boolean checkBankCard = checkBankCard("6217991100001804444");
		System.out.println(checkBankCard);
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Donate to developers 

Driven by interest, I write 免费something with joy and sweat. I hope you like my work and can support it at the same time. Of course, if you have money to support a money field (support Alipay, WeChat, and the buckle group), if you have no money to support a personal field, thank you.

 

Personal homepage : http://knight-black-bob.iteye.com/



 
 
 Thank you for your sponsorship, I will do better!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326927838&siteId=291194637