This commit is contained in:
Looly 2024-06-09 18:10:18 +08:00
parent 61a7767ca3
commit 8a7161c3d6
3 changed files with 31 additions and 32 deletions

View File

@ -23,26 +23,40 @@ import org.dromara.hutool.core.text.StrUtil;
* <li>把步骤1种获得的乘积的各位数字与原号码中未乘2的各位数字相加</li>
* <li>如果步骤2得到的总和模10为0则校验通过</li>
* </ol>
*
*/
public class Luhn {
/**
* 校验字符串
*
* @param withCheckDigitString 含校验数字的字符串
* @param strWithCheckDigit 含校验数字的字符串
* @return true - 校验通过false-校验不通过
* @throws IllegalArgumentException 如果字符串为空或不是8~19位的数字
*/
public static boolean check(final String withCheckDigitString) {
if(StrUtil.isBlank(withCheckDigitString)){
public static boolean check(final String strWithCheckDigit) {
if (StrUtil.isBlank(strWithCheckDigit)) {
return false;
}
if(!ReUtil.isMatch(PatternPool.NUMBERS, withCheckDigitString)){
if (!ReUtil.isMatch(PatternPool.NUMBERS, strWithCheckDigit)) {
// 必须为全数字
return false;
}
return sum(withCheckDigitString) % 10 == 0;
return sum(strWithCheckDigit) % 10 == 0;
}
/**
* 计算校验位数字<br>
* 忽略已有的校验位数字根据前N位计算最后一位校验位数字
*
* @param str 被检查的数字
* @param withCheckDigit 是否含有校验位
* @return 校验位数字
*/
public static int getCheckDigit(String str, final boolean withCheckDigit) {
if (withCheckDigit) {
str = str.substring(0, str.length() - 1);
}
return 10 - (sum(str + "0") % 10);
}
/**
@ -54,7 +68,8 @@ public class Luhn {
private static int sum(final String str) {
final char[] strArray = str.toCharArray();
final int n = strArray.length;
int sum = strArray[n - 1] - '0';;
int sum = strArray[n - 1] - '0';
;
for (int i = 2; i <= n; i++) {
int a = strArray[n - i] - '0';
// 偶数位乘以2

View File

@ -1,25 +0,0 @@
/*
* Copyright (c) 2024. looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* https://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.data;
/**
* 银行卡号Bank Card Number封装参考标准
* <ul>
* <li>银行卡发卡行标识代码及卡号JR/T 00082000https://std.samr.gov.cn/hb/search/stdHBDetailed?id=C362C05F3E35A68DE05397BE0A0A9B00</li>
* <li>ISO 7812-1:1997https://www.iso.org/standard/56907.html</li>
* </ul>
*
*
*/
public class BCN {
}

View File

@ -26,4 +26,13 @@ class LuhnTest {
assertFalse(Luhn.check("abc"));
assertFalse(Luhn.check("622576000821952a"));
}
@Test
void getCheckDigitTest() {
int checkDigit = Luhn.getCheckDigit("6225760008219524", true);
assertEquals(4, checkDigit);
checkDigit = Luhn.getCheckDigit("622576000821952", false);
assertEquals(4, checkDigit);
}
}