Jump to content

Luhn algorithm: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Kle0012 (talk | contribs)
Kle0012 (talk | contribs)
Line 54: Line 54:
class Luhn
class Luhn
def self.check_luhn(s)
def self.check_luhn(s)
alternate, total = false, 0
total = 0
s.gsub(/\D/, '').reverse.split(//).each do |c|
s.gsub(/\D/, '').reverse.split(//).each_with_index do |c, i|
total += alternate ? double_digit(c.to_i) : c.to_i
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 2255, 3366 or 4477).

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:

  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. Sum the digits of the products together with the undoubled digits from the original number.
  3. 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:

  1. Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
  2. 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
  3. 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

References