Jump to content

Luhn algorithm

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Randomguy-2650 (talk | contribs) at 15:23, 31 August 2024 (Added code block for JavaScript). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, named after its creator, IBM scientist Hans Peter Luhn, is a simple check digit formula used to validate a variety of identification numbers. It is described in US patent 2950048A, granted on 23 August 1960.[1]

The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812-1.[2] 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 mistyped or otherwise incorrect numbers.

Description

The check digit is computed as follows:

  1. If the number already contains the check digit, drop that digit to form the "payload". The check digit is most often the last digit.
  2. With the payload, start from the rightmost digit. Moving left, double the value of every second digit (including the rightmost digit).
  3. Sum the values of the resulting digits.
  4. The check digit is calculated by , where s is the sum from step 3. This is the smallest number (possibly zero) that must be added to to make a multiple of 10. Other valid formulas giving the same value are , , and . Note that the formula will not work in all environments due to differences in how negative numbers are handled by the modulo operation.

Example for computing check digit

Assume an example of an account number 1789372997 (just the "payload", check digit not yet included):

7 9 9 2 7 3 9 8 7 1
Multipliers 2 1 2 1 2 1 2 1 2 1
= = = = = = = = = =
14 9 18 2 14 3 18 8 14 1
Sum digits 5 (1+4) 9 9 (1+8) 2 5 (1+4) 3 9 (1+8) 8 5 (1+4) 1

The sum of the resulting digits is 56.

The check digit is equal to .

This makes the full account number read 17893729974.

Example for validating check digit

  1. Drop the check digit (last digit) of the number to validate. (e.g. 17893729974 → 1789372997)
  2. Calculate the check digit (see above)
  3. Compare your result with the original check digit. If both numbers match, the result is valid. (e.g. (givenCheckDigit = calculatedCheckDigit) ⇔ (isValidCheckDigit)).

Strengths and weaknesses

The Luhn algorithm will detect all single-digit errors, 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 most of the possible twin errors (it will not detect 2255, 3366 or 4477).

Other, more complex check-digit algorithms (such as the Verhoeff algorithm and the Damm 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 pad to a specific number of digits (by converting 1234 to 0001234 for instance) can perform Luhn validation before or after the padding and achieve the same result.

The algorithm appeared in a United States Patent[1] for a simple, hand-held, mechanical device for computing the checksum. 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.

Pseudocode implementation

The following function takes a card number, including the check digit, as an array of integers and outputs true if the check digit is correct, false otherwise.

function isValid(cardNumber[1..length])
    sum := 0
    parity := length mod 2
    for i from 1 to length do
        if i mod 2 != parity then
            sum := sum + cardNumber[i]
        elseif cardNumber[i] > 4 then
            sum := sum + 2 * cardNumber[i] - 9
        else
            sum := sum + 2 * cardNumber[i]
        end if
    end for
    return cardNumber[length] == (10 - (sum mod 10))
end function

Code implementation

bool IsValidLuhn(int[] digits)
{
    int checkDigit = 0;
    for (int i = digits.Length - 2; i >= 0; --i)
    {
        checkDigit +=
            (i & 1) == (digits.Length & 1)
                ? digits[i] > 4 ? digits[i] * 2 - 9 : digits[i] * 2
                : digits[i];
    }

    return (10 - checkDigit % 10) % 10 == digits[^1];
}
public static boolean isValidLuhn(String number) {
    int n = number.length();
    int total = 0;
    boolean even = true;
    // iterate from right to left, double every 'even' value
    for (int i = n - 2; i >= 0; i--) {
        int digit = number.charAt(i) - '0';
        if (digit < 0 || digit > 9) {
            // value may only contain digits
            return false;
        }
        if (even) {
            digit <<= 1; // double value
        }
        even = !even;
        total += digit > 9 ? digit - 9 : digit;
    }
    int checksum = number.charAt(n - 1) - '0';
    return (total + checksum) % 10 == 0;
}
function luhnCheck(input: number): boolean {
  const number = input.toString();
  const digits = number.replace(/\D/g, '').split('').map(Number);
  let sum = 0;
  let isSecond = false;
  for (let i = digits.length - 1; i >= 0; i--) {
    let digit = digits[i];
    if (isSecond) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    sum += digit;
    isSecond = !isSecond;
  }
  return sum % 10 === 0;
}
function luhnCheck(input) {
  const number = input.toString();
  const digits = number.replace(/\D/g, "").split("").map(Number);
  let sum = 0;
  let isSecond = false;
  for (let i = digits.length - 1; i >= 0; i--) {
    let digit = digits[i];
    if (isSecond) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    sum += digit;
    isSecond = !isSecond;
  }
  return sum % 10 === 0;
}
"""Verhoeff's algorithm implementation for checksum digit calculation"""


class LuhnAlgorithm(BaseChecksumAlgorithm):
    """
    Class to validate a number using Luhn algorithm.

    Arguments:
        input_value (str): The input value to validate.

    Returns:
        bool: True if the number is valid, False otherwise.
    """
    def __init__(self, input_value: str) -> None:
        self.input_value = input_value.replace(' ', '')

    def last_digit_and_remaining_numbers(self) -> tuple:
        """Returns the last digit and the remaining numbers"""
        return int(self.input_value[-1]), self.input_value[:-1]

    def __checksum(self) -> int:
        last_digit, remaining_numbers = self.last_digit_and_remaining_numbers()
        nums = [int(num) if idx % 2 != 0 else int(num) * 2 if int(num) * 2 <= 9
                else int(num) * 2 % 10 + int(num) * 2 // 10
                for idx, num in enumerate(reversed(remaining_numbers))]

        return (sum(nums) + last_digit) % 10 == 0

    def verify(self) -> bool:
        """Verify a number using Luhn algorithm"""
        return self.__checksum()

Uses

The Luhn algorithm is used in a variety of systems, including:

References

  1. ^ a b US patent 2950048A, Luhn, Hans Peter, "Computer for Verifying Numbers", published 23 August 1960, issued 23 August 1960 
  2. ^ "Annex B: Luhn formula for computing modulus-10 "double-add-double" check digits". Identification cards — Identification of issuers — Part 1: Numbering system (standard). International Organization for Standardization & International Electrotechnical Commission. January 2017. ISO/IEC 7812-1:2017.
  3. ^ Raj, Deepak; Figiel, Troy (14 November 2022). "Verhoeff's algorithm implementation for checksum digit calculation". GitHub. Archived from the original on 25 July 2024. Retrieved 25 July 2024.
  4. ^ Publication 199: Intelligent Mail Package Barcode (IMpb) Implementation Guide for Confirmation Services and Electronic Payment Systems (PDF) (28th ed.). United States: United States Postal Service. 10 October 2023. Archived (PDF) from the original on 17 November 2023. Retrieved 29 November 2023.
  5. ^ Albanese, Ilenia (10 August 2022). "A cosa serve la Partita Iva? Ecco cosa sapere" [What is a VAT number for? Here's what to know]. Partitaiva.it (in Italian). Archived from the original on 29 June 2024. Retrieved 29 June 2024.