tanszek:oktatas:techcomm:luhn_algortithm_to_protect_credit_card_numbers

This is an old revision of the document!


To check if a credit card number is valid, you can use the Luhn algorithm. This is a simple checksum formula used to identify mistyped or incorrect numbers. Here’s how it works:

Steps of the Luhn Algorithm

1. Reverse the order of the card number's digits. 2. Double every second digit, starting from the first digit (which is now the second digit of the reversed number). 3. If any doubled value is greater than 9, subtract 9 from it (alternatively, add the digits together; e.g., 12 becomes 1 + 2 = 3). 4. Sum all the digits (including both doubled and undoubled digits). 5. Check if the sum is divisible by 10. If it is, the card number is valid.

Example

Let’s check if the following card number is valid: 4539 1488 0343 6467

1. Reverse it: 7646 3430 8841 9354 2. Double every second digit: 7, 12, 4, 12, 6, 6, 3, 6, 8, 16, 4, 2, 9, 6, 5, 8 3. For doubled values greater than 9 (12, 12, 16), add their digits: 7, 3, 4, 3, 6, 6, 3, 6, 8, 7, 4, 2, 9, 6, 5, 8 4. Sum: 70 5. Since 70 is divisible by 10, the card number is valid.

Quick Check Code in Python

Here's a simple Python code to check if a credit card number is valid using the Luhn algorithm:

def luhn_check(card_number):
    digits = [int(d) for d in str(card_number)][::-1]
    checksum = sum(digits[0::2]) + sum(sum(divmod(2 * d, 10)) for d in digits[1::2])
    return checksum % 10 == 0

# Example usage
card_number = "4539148803436467"
print("Valid" if luhn_check(card_number) else "Invalid")

This code will output whether the credit card number is valid or invalid based on the Luhn algorithm.

tanszek/oktatas/techcomm/luhn_algortithm_to_protect_credit_card_numbers.1730825087.txt.gz · Last modified: 2024/11/05 16:44 by knehez