Graham King

Solvitas perambulum

Luhn formula

credit-card

A credit card number must be from 13 to 16 digits long. The last digit of the number is the check digit. That number is calculated from an algorithm (called the Luhn formula or MOD 10) on the other numbers. This is to spot typos when a user enters a number, and I assume was to allow detecting an error reading the magnetic stripe when a card is swiped.

The MOD 10 check does not offer security, it offers error detection. Think of it as fullfilling the same role as a CRC in software.

To calculate the check digit:

First drop the last digit from the card number (because that’s what we are trying to calculate)

Reverse the number

Multiply all the digits in odd positions (The first digit, the third digit, etc) by 2.

If any one is greater than 9 subtract 9 from it.

Sum those numbers up

Add the even numbered digits (the second, fourth, etc) to the number you got in the previous step

The check digit is the amount you need to add to that number to make a multiple of 10. So if you got 68 in the previous step the check digit would be 2. You can calculate the digit in code using checkdigit = ((sum / 10 + 1) * 10 – sum) % 10

For an example of this in practice download the code to the credit card number generator.

Credit card numbers are a special type of ISO 7812 numbers.