A while back now I had to write a system to process credit cards. Since the software was capturing the card number itself it could perform some initial checking on the number to ensure that the user hadn’t made a trivial typing error.
Apart from checking you have the appropriate number of digits for the card the easiest check to do is called the Luhn check (aka mod-10 or modulus 10). Technically the Luhn algorithm is a hash function but it should not be considered secure, instead it is useful for catching simple data entry problems.
The Luhn algorithm works like this:
- Write down the number to test placing each digit in a separate column.
- Starting at the right hand end double every other number (shown in bold).
- Add together the digits of all the numbers in step 2 (e.g. 14=1+4=5). Then add together all the digits. Write the result in the last column.
- If the total in step 3 ends with a zero (e.g. the total modulo 10 = 0, hence the name) the number passes the test.
Step 1 | 3 | 7 | 8 | 2 | 8 | 2 | 2 | 4 | 6 | 3 | 1 | 0 | 0 | 0 | 5 | |
Step 2 | 3 | 14 | 8 | 4 | 8 | 4 | 2 | 8 | 6 | 6 | 1 | 0 | 0 | 0 | 5 | |
Step 3 | 3 | 5 | 8 | 4 | 8 | 4 | 2 | 8 | 6 | 6 | 1 | 0 | 0 | 0 | 5 | 60 |
The last digit (5 in this example) is called the check digit. When the bank is generating a credit card number this is the digit they have to tweak in order to make the over all number pass the Luhn check. The way the check digit is calculated is very similar to the check calculation except in step three the result (which would be 55 in the example) is multiplied by 9 to give 495. The last digit of the result (e.g. 5) is the check digit.
Different credit cards have different numbers of digits and they start with different codes. For example Visa cards always start with a 4. In order to properly test a payment system therefore you need some valid numbers that won’t get tested. The table below lists some that are commonly used.
Card Type | Card Number |
---|---|
American Express | 378282246310005 |
American Express | 371449635398431 |
American Express Corporate | 378734493671000 |
Australian BankCard | 5610591081018250 |
Diners Club | 30569309025904 |
Diners Club | 38520000023237 |
Discover | 6011111111111117 |
Discover | 6011000990139424 |
JCB | 3530111333300000 |
JCB | 3566002020360505 |
MasterCard | 5555555555554444 |
MasterCard | 5105105105105100 |
Visa | 4111111111111111 |
Visa | 4012888888881881 |
Visa | 4222222222222 |