Luhn algorithm: Difference between revisions
Line 54: | Line 54: | ||
class Luhn |
class Luhn |
||
def self.check_luhn(s) |
def self.check_luhn(s) |
||
total = 0 |
|||
s.gsub(/\D/, '').reverse.split(//). |
s.gsub(/\D/, '').reverse.split(//).each_with_index do |c, i| |
||
total += |
total += (i + 1 % 2 == 1 ? c.to_i : (c.to_i > 4 ? (c.to_i * 2) % 10 + 1 : c.to_i * 2)) |
||
alternate = !alternate |
|||
end |
end |
||
(total % 10) == 0 |
(total % 10) == 0 |
||
end |
|||
private |
|||
def self.double_digit(i) |
|||
i *= 2 |
|||
i = i % 10 + 1 if i > 9 |
|||
i |
|||
end |
end |
||
end |
end |
Revision as of 11:32, 11 March 2010
The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn and described in U.S. Patent No. 2,950,048, filed on January 6, 1954, and granted on August 23, 1960.
The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812-1[1]. It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from collections of random digits.
Strengths and weaknesses
The Luhn algorithm will detect any single-digit error, as well as almost all transpositions of adjacent digits. It will not, however, detect transposition of the two-digit sequence 09 to 90 (or vice versa). It will detect 7 of the 10 possible twin errors (it will not detect 22 ↔ 55, 33 ↔ 66 or 44 ↔ 77).
Other, more complex check-digit algorithms (such as the Verhoeff algorithm) can detect more transcription errors. The Luhn mod N algorithm is an extension that supports non-numerical strings.
Because the algorithm operates on the digits in a right-to-left manner and zero digits affect the result only if they cause shift in position, zero-padding the beginning of a string of numbers does not affect the calculation. Therefore, systems that normalize to a specific number of digits by converting 1234 to 00001234 (for instance) can perform Luhn validation before or after the normalization and achieve the same result.
The algorithm appeared in a US Patent for a hand-held, mechanical device for computing the checksum. It was therefore required to be rather simple. The device took the mod 10 sum by mechanical means. The substitution digits, that is, the results of the double and reduce procedure, were not produced mechanically. Rather, the digits were marked in their permuted order on the body of the machine.
Informal explanation
The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test:
- Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
- Sum the digits of the products together with the undoubled digits from the original number.
- If the total ends in 0 (put another way, if the total modulo 10 is equal to 0), then the number is valid according to the Luhn formula; else it is not valid.
As an illustration, if the account number is 49927398716, it will be validated as follows:
- Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
- Sum all the individual digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70
- Take the sum modulo 10: 70 mod 10 = 0; the account number is valid.
Mod 10+5 Variant
Some credit cards use the "Mod 10 plus 5" variant to extend the space of valid card numbers.[citation needed] In this variant, if the sum ends in 0 or 5, the number is considered valid.
Implementation of standard Mod 10
Python variant:
def is_mod10(cc):
dub, tot = 0, 0
for i in range(len(cc) - 1, -1, -1):
for c in str((dub + 1) * int(cc[i])):
tot += int(c)
dub = (dub + 1) % 2
return (tot % 10) == 0
Ruby variant:
class Luhn
def self.check_luhn(s)
total = 0
s.gsub(/\D/, '').reverse.split(//).each_with_index do |c, i|
total += (i + 1 % 2 == 1 ? c.to_i : (c.to_i > 4 ? (c.to_i * 2) % 10 + 1 : c.to_i * 2))
end
(total % 10) == 0
end
end
Java variant:
public static boolean isValidCC(String num) {
final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}};
int sum = 0, flip = 0;
for (int i = num.length() - 1; i >= 0; i--, flip++)
sum += sumTable[flip & 0x1][Character.digit(num.charAt(i), 10)];
return sum % 10 == 0;
}
C# variant:
public static int CalculateCheckDigit(string value)
{
int ConSum = 0;
bool doubleDigit = true; // check digit is absent before generation
for (int i = value.Length - 1; i >= 0; i--)
{
int digit = 0;
Int32.TryParse(value[i].ToString(), out digit);
int ConAdd = digit * (doubleDigit? 2: 1);
doubleDigit = !doubleDigit;
ConSum += (ConAdd > 9 ? ConAdd -= 9 : ConAdd);
}
return ((ConSum % 10) == 0 ? 0 : (10 - (ConSum % 10)));
}
JavaScript variant:
var cardValid = function( cardNo ){
var sum = 0, iNum;
for( var i = cardNo.length-1; i>=0; i-- ){
iNum = parseInt(cardNo[i]);
sum += i%2?iNum:iNum>4?iNum*2%10+1:iNum*2;
}
return !(sum%10);
};
Delphi variant:
function LuhnCheckDigit(const AInputString: string): Byte;
var
i: Integer;
LSum: Integer;
LDigit: Integer;
begin
i := 0;
LSum := 0;
while i < Length(AInputString) do
begin
LDigit := StrToInt(AInputString[Length(AInputString) - i]);
LDigit := LDigit * (1 + (i mod 2));
LSum := LSum + (LDigit div 10) + (LDigit mod 10);
inc(i);
end;
Result := LSum mod 10;
end;
Excel variant:
=RIGHT((LEFT(A1)+MID(A1;3;1)+MID(A1;5;1)+MID(A1;8;1)+MID(A1;10;1))*2-((LEFT(A1)*1>4)+(MID(A1;3;1)*1>4)+(MID(A1;5;1)*1>4)+(MID(A1;8;1)*1>4)+(MID(A1;10;1)*1>4))*9+MID(A1;2;1)+MID(A1;4;1)+MID(A1;6;1)+MID(A1;9;1)+RIGHT(A1))="0"
Can be used for condition formating, returns TRUE or FALSE.
Other implementations
- Luhn generation and validation in PostgreSQL dialect
- Luhn validation code in Actionscript2, with generation code
- Luhn validation code in Apex
- Luhn validation code in C
- Luhn validation code in C#
- Luhn validation code in VB.Net and C# with Card Identification
- Luhn validation code in ColdFusion
- Luhn validation code in FileMaker Pro
- Luhn validation code in F#
- Luhn validation code in Common Lisp
- Luhn validation code in Java
- Luhn/CUSPIP validation code in Java, with test cases - varies from algorithm above in counting from left to determine which digits to double
- JavaScript Credit Card Validation
- Luhn validation code in JavaScript
- Luhn validation and card type determination code in Prototype JavaScript by Thomas Fuchs
- Luhn generation code in JavaScript, with test page for IMEI numbers
- Luhn validation and creation code in Haskell, as a library
- Luhn validation code in MS Excel
- Luhn validation code in MS Excel VBA
- Luhn validation code in Perl
- Luhn validation code in Perl
- Luhn validation code in PowerShell
- Luhn validation code in ProvideX
- Luhn validation code in PHP
- Luhn validation code in PureBasic
- Luhn validation code in Python
- Luhn validation code in Python, as a library
- Luhn validation code in Ruby for French SIRET numbers (
checksum
method) - Luhn validation code in Ruby
- Luhn validation code in Ruby, with card type check
- Luhn validation code in Transact-SQL
- Luhn validation code in VBScript (ASP)
- Luhn validation code in ABAP
- Template for applying the Luhn algorithm in XSLT
- Alternative Luhn validation code in C, awk and Python
- App Engine Python Luhn Algorithm validator
References
- U.S. patent 2,950,048, Computer for Verifying Numbers, Hans P. Luhn, August 23, 1960.