28/03/2014

Credit Card Number Detection Algorithm (Luhn Algorithm)

I would like to share with you an algorithm that I came across by chance at work. It is used to detect valid credit card numbers. Apparently credit card numbers are not generated randomly but they follow an algorithm and these numbers can be detected with an algorithm developed by Hans Peter Luhn at IBM in 1950s.

This algorithm is known also as "modulus 10" or "mod 10" algorithm. It is pretty simple and is widely used to conceal credit card numbers for security reasons. We always see in online shopping e-commerce sites that our credit card number is displayed back to us with only the last 4 digits visible and the rest is masked with an asterisk *. This is done with the help of this algorithm.

How it works?
  1. From the right-most number moving to the left, double the value of every second number. (Right-most digit is called the check digit)
    1. If the result of this doubling operation is greater than 9, sum the digits of the result.
  2. Sum all the digits.
  3. If the total modulus 10 is 0, then it is a valid credit card number.
Let's take an example credit card number that is valid and see the calculation steps: 2012444444444444

CC number
2
0
1
2
4
4
4
4
4
4
4
4
4
4
4
4
Double every second digit
4
0
2
2
8
4
8
4
8
4
8
4
8
4
8
4
Sum of digits
4
0
2
2
8
4
8
4
8
4
8
4
8
4
8
4
=80

Let's take another number that is not a valid example: 1010666666666666

CC number1010666666666666
Double every second digit2020126126126126126126
Sum of digits2020363636363636=58