LuhnアルゴリズムまたはLuhn式(作成者:IBMの科学者Hans Peter Luhn)は、「モジュラス10」または「mod 10」アルゴリズムとしても知られ、さまざまな識別番号の検証に使用されるシンプルなチェックディジット式です。 [a]その目的は、人間が数字を入力する際に、コンピュータがエラーを迅速にチェックできるような番号体系を設計することです。
このアルゴリズムはパブリックドメインであり、現在広く使用されています。ISO /IEC 7812-1で規定されています。[2]これは暗号的に安全なハッシュ関数を意図したものではなく、悪意のある攻撃ではなく、偶発的なエラーから保護するために設計されました。ほとんどのクレジットカード番号と多くの政府発行の身分証明書番号は、有効な番号と誤入力された番号やその他の誤った番号を区別するための簡単な方法としてこのアルゴリズムを使用しています。
チェックディジットは次のように計算されます
口座番号1789372997(「ペイロード」のみ、チェックデジットはまだ含まれていない)の例を想定します。
結果の数字の合計は56です
チェックディジットは です
これにより、口座番号全体は17893729974になります。
Luhnアルゴリズムは、すべての1桁のエラーと、隣接する数字のほぼすべての転置を検出します。ただし、09から90(またはその逆)の2桁の転置は検出しません。起こりうる双子エラーのほとんどを検出します(22↔55、33↔66、または44↔77は検出しません)。
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.
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 - 1) 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)) mod 10)
end function
The Luhn algorithm is used in a variety of systems, including: