信用卡验证(卢恩算法)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了信用卡验证(卢恩算法)相关的知识,希望对你有一定的参考价值。

Uses the Luhn formula to quickly validate a credit card. Basically all the digits except for the last one are summed together and the output is a single digit (0 to 9). This digit is compared with the last digit ensure a proper credit card number is entered (Does not actually confirm that is is a real number, just that it is likely to be one. Example: Entering "4000-0000-0000-0002" will pass the check, but "4000-0000-0000-0003" will not pass.)
  1. function CheckCC(CCNo)
  2.  
  3. Dim i, w, x, y
  4. y = 0
  5.  
  6. 'Ensure the proper format of the input
  7. CCNo = Replace(Replace(Replace(CStr(CCNo), "-", ""), " ", ""), ".", "")
  8.  
  9. 'Process digits from right to left, drop last digit if total length is even
  10. w = 2 * (Len(CCNo) Mod 2)
  11. For i = Len(CCNo) - 1 To 1 Step -1
  12. x = Mid(CCNo, i, 1)
  13. if IsNumeric(x) Then
  14. Select Case (i Mod 2) + w
  15. Case 0, 3 'Even Digit - Odd where total length is odd (eg. Visa vs. Amx)
  16. y = y + CInt(x)
  17. Case 1, 2 'Odd Digit - Even where total length is odd (eg. Visa vs. Amx)
  18. x = CInt(x) * 2
  19. if x > 9 Then
  20.  
  21. 'Break the digits (eg. 19 becomes 1 + 9)
  22. y = y + (x 10) + (x - 10)
  23. Else
  24. y = y + x
  25. End if
  26. End Select
  27. End if
  28. Next
  29.  
  30. 'Return the 10's complement of the total
  31. y = 10 - (y Mod 10)
  32. if y > 9 Then y = 0
  33. CheckCC = (CStr(y) = Right(CCNo, 1))
  34.  
  35. End function

以上是关于信用卡验证(卢恩算法)的主要内容,如果未能解决你的问题,请参考以下文章

汉斯•彼得•卢恩与哈希算法的诞生

卢恩公式(算法)

如何使用 Luhn 算法创建信用卡验证器?

CreditCardAttribute 使用哪种算法进行信用卡号格式验证

当我们使用 Luhn 算法验证信用卡时,为啥要反转数字?

信用卡长/字符串验证[关闭]