介绍
本文的目的是解释如何使用 Python 编写一个简单的信用卡验证器。用于验证卡号的算法称为Luhn
算法
关于 Luhn 算法
Luhn 算法由德国计算机科学家 Hans Peter Luhn 于 1954 年开发。该算法也称为“模数 10 算法”,是一种校验和公式,用于验证包括信用卡号在内的各种识别号码。
大多数信用卡和许多政府识别号码都使用该算法作为区分有效号码与输入错误或其他错误号码的简单方法。它并非旨在成为加密安全的散列函数;相反,它的创建是为了检测意外错误,而不是防御恶意攻击
算法的工作原理
1.Luhn 算法从称为校验位的最后一位开始。然后从该校验位 ( ←) 向左移动,将偶数索引处的每个数字的值加倍
2.如果这个加倍运算的结果大于 9(例如6 × 2 = 12),则从结果中减去 9(例如12: 12 - 9 = 3),或者等价地添加结果的数字(例如, 12: 1 + 2 =3 )
3.现在对所有数字求和(包括校验位)
4.如果总数可以被 10 整除,则该数字有效;否则无效
使用 Python 实现 Luhn 算法
下面的解决方案将采用一个名为“ credit_number ”的字符串参数,它表示将被验证的信用卡号。下面的伪代码将帮助解释每行代码所采取的步骤
1.将字符串更改为列表数据类型
2.删除最后一位(校验位)
3.反转剩余数字
4.偶数指数两位数
5.如果超过 9,则减去 9
6.将校验位添加回列表
7.将所有数字相加
8.如果总和能被 10 整除,那么它是有效的;否则,无效
def validate_credit_card(card_number: str) -> bool:
"""This function validates a credit card number."""
# 1. Change datatype to list[int]
card_number = [int(num) for num in card_number]
# 2. Remove the last digit:
checkDigit = card_number.pop(-1)
# 3. Reverse the remaining digits:
card_number.reverse()
# 4. Double digits at even indices
card_number = [num * 2 if idx % 2 == 0
else num for idx, num in enumerate(card_number)]
# 5. Subtract 9 at even indices if digit is over 9
# (or you can add the digits)
card_number = [num - 9 if idx % 2 == 0 and num > 9
else num for idx, num in enumerate(card_number)]
# 6. Add the checkDigit back to the list:
card_number.append(checkDigit)
# 7. Sum all digits:
checkSum = sum(card_number)
# 8. If checkSum is divisible by 10, it is valid.
return checkSum % 10 == 0
if __name__ == '__main__':
# American Express
print(validate_credit_card('378282246310005')) # True
print(validate_credit_card('371449635398431')) # True
# American Express Corporate
print(validate_credit_card('378734493671000')) # True
# Australian BankCard
print(validate_credit_card('5610591081018250')) # True
# Diners Club
print(validate_credit_card('30569309025904')) # True
print(validate_credit_card('38520000023237')) # True
# Discover
print(validate_credit_card('6011111111111117')) # True
print(validate_credit_card('6011000990139424')) # True
# MasterCard
print(validate_credit_card('5555555555554444')) # True
print(validate_credit_card('5105105105105100')) # True
# Visa
print(validate_credit_card('4111111111111111')) # True
print(validate_credit_card('4012888888881881')) # True
# Invalid Credit Card Number
print(validate_credit_card('7762888103111881')) # False
print(validate_credit_card('37612555227841800')) # False
发表评论 取消回复