Detailed explanation of android bank card number verification algorithm

  • 2021-10-13 08:50:30
  • OfStack

The first 6 digits of the current 16-digit UnionPay card number are between 622126 and 622925, the 7-15 digits are customized by the bank, which may be the issuing branch, issuing outlet and issuing serial number, and the 16th digit is the check code.

The 16-bit card number check bits are calculated by Luhm check method:

1. Number the 15-digit card number without parity digit from right 1 to 15, and multiply the number on the odd digit number by 2
2. Add all 10 bits of odd bit product, and add all the numbers on even bits
3. The addition and addition parity bits can be divisible by 10.


public class CheckIdCard {
  /**
   *  Verify the bank card number 
   *
   * @param cardId
   * @return
   */
  public static boolean checkBankCard(String cardId) {
    char bit = getBankCardCheckCode(cardId
        .substring(0, cardId.length() - 1));
    if (bit == 'N') {
      return false;
    }
    return cardId.charAt(cardId.length() - 1) == bit;
  }

  /**
   *  Adopt the bank card number without check digit  Luhm  The check algorithm obtains the check bit 
   *
   * @param nonCheckCodeCardId
   * @return
   */
  public static char getBankCardCheckCode(String nonCheckCodeCardId) {
    if (nonCheckCodeCardId == null
        || nonCheckCodeCardId.trim().length() == 0
        || !nonCheckCodeCardId.matches("\\d+")) {
      //  If the data is not returned N
      return 'N';
    }
    char[] chs = nonCheckCodeCardId.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');
  }
}


Related articles: