Created by the german IBM scientist Hans Peter Luhn, the Luhn Algorithm is a checksum formula being used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers etc.
In this blog post, I will show you some functions I created that uses this algorithm. It can be used to calculate a checksum digit from a number, as well as validate numbers using the Luhn Algorithm checksum validation.
First off we have the main function, Get-LuhnChecksum. This function takes a number (uint64) as input and calculates the Luch checksum. This checksum is then used by either New-LuhnChecksumDigit to get the checksum digit of a number, or by Test-IsLuhnValid to validate a number, such as a credit card number.
Let’s demonstrate. We start off with a random number; 387234876. Let’s calculate the Luhn checksum digit for this number:
As you see, the result is 2. This is our checksum digit. We append this number to the end of our original number, so we now have 3872348762. We can further validate this number:
There you go. We have created a number with a Luhn checksum digit (last digit), and we have the means to validate it to see that it correct.
As stated earlier, this algorithm can be used to validate credit card numbers. It will detect any single digit error as well as almost all transpositions of adjacent digits. But since it’s not perfect, if you need credit card number validations you should add additional checks (such as number length).
Enjoy. If you have any questions, suggestions or bug-reports, please let me know in the comments section below (or on Twitter).
Oh.. and you need this helper-function as well: