Upcoming SlideShare
×

# Luhn algorithm

3,963 views

Published on

Published in: Technology
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
3,963
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
28
0
Likes
0
Embeds 0
No embeds

No notes for slide

### Luhn algorithm

1. 1. Các tài liệu về thuật toán Luhn 2008 Các tài liệu về thuật toán Luhn Table of Contents 1. Luhn algorithm .................................................................................................................. 2 1.1. Strengths and weaknesses....................................................................................................... 2 1.2. Informal explanation................................................................................................................... 2 1.3. Example ....................................................................................................................................... 3 1.4. Implementation ........................................................................................................................... 4 2. Credit Card Validation - Check Digits .............................................................................. 6 2.1. Prefix, Length, and Check Digit Criteria.................................................................................. 6 2.2. LUHN Formula (Mod 10) for Validation of Primary Account Number ................................ 7 3. How To Generate *Valid* Credit Card Numbers .............................................................. 9 3.1. Typical credit card anatomy ...................................................................................................... 9 3.2. What is the “Luhn” or “Mod 10″ check? ................................................................................ 10 3.3. Credit card numbers valid or invalid? .................................................................................... 10 3.4. Closing remarks ........................................................................................................................ 12 3.5. Resources and References .................................................................................................... 13 4. Actionscript Credit Card Validation - Luhn Check.........................................................14 Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 1
2. 2. Các tài liệu về thuật toán Luhn 2008 1. Luhn algorithm 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 and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn and described in U.S. Patent 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 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. 1.1. 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). 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 only affect the result 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. 1.2. 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 rightmost digit (which is the check digit) and moving left, double the value of every even-positioned digit. For any digits that thus become 10 or more, take the two numbers and add them together. For example, 1111 becomes 2121, while 8763 becomes 7733 (from 2×6=12 → 1+2=3 and 2×8=16 → 1+6=7). 2. Add all these digits together. For example, if 1111 becomes 2121, then 2+1+2+1 is 6; and 8763 becomes 7733, so 7+7+3+3 is 20. 3. If the total ends in 0 (put another way, if the total modulus 10 is congruent to 0), then the number is valid according to the Luhn formula; else it is not valid. So, 1111 is not valid (as shown above, it comes out to 6), while 8763 is valid (as shown above, it comes out to 20). Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 2
3. 3. Các tài liệu về thuật toán Luhn 2008 1.3. Example Consider the example identification number 446-667-651. The first step is to double every other digit, counting from the second-to-last digit and moving left, and sum the digits in the result. The following table shows this step (highlighted rows indicating doubled digits): Digit Double Substitute Result 1 1 1 5 10 1+0 1 6 6 6 7 14 1+4 5 6 6 6 6 12 1+2 3 6 6 6 4 8 8 8 4 4 4 Total Sum: 40 The sum of 40 is divided by 10; the remainder is 0, so the number is valid. A lookup table (i.e. calculate Double, Reduce, and Sum of digits only once and for all) can be used (0123456789 is mapped to 0246813579) Digit Double Substitute Result 0 0 0 0 1 2 2 2 2 4 4 4 3 6 6 6 4 8 8 8 5 10 1+0 1 6 12 1+2 3 7 14 1+4 5 8 16 1+6 7 9 18 1+8 9 Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 3
4. 4. Các tài liệu về thuật toán Luhn 2008 1.4. Implementation This C# function implements the algorithm described above, returning true if the given array of digits represents a valid Luhn number, and false otherwise. bool CheckNumber(int[] digits) { int sum = 0; bool alt = false; for(int i = digits.Length - 1; i >= 0; i--) { if(alt) { digits[i] *= 2; if(digits[i] > 9) { digits[i] -= 9; } } sum += digits[i]; alt = !alt; } return sum % 10 == 0; } The following is an algorithm (in C#) to generate a number that passes the Luhn algorithm. It fills an array with random digits then computes the sum of those numbers as shown above and places the difference 10-sum (modulo 10) in the last element of the array. int[] CreateNumber(int length) { Random random = new Random(); int[] digits = new int[length]; // For loop keeps default value of zero for last slot in array for(int i = 0; i < length - 1; i++) { digits[i] = random.Next(10); } int sum = 0; bool alt = true; for(int i = length - 2; i >= 0; i--) { if(alt) { int temp = digits[i]; temp *= 2; if(temp > 9) { temp -= 9; } sum += temp; } else { sum += digits[i]; } alt = !alt; } int modulo = sum % 10; Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 4
5. 5. Các tài liệu về thuật toán Luhn 2008 if(modulo > 0) { digits[length-1] = 10 - modulo; } // No else reqd - keep default value of zero for digits[length-1] return digits; } Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 5
6. 6. Các tài liệu về thuật toán Luhn 2008 2. Credit Card Validation - Check Digits This document outlines procedures and algorithms for Verifying the accuracy and validity of credit card numbers. Most credit card numbers are encoded with a "Check Digit". A check digit is a digit added to a number (either at the end or the beginning) that validates the authenticity of the number. A simple algorithm is applied to the other digits of the number which yields the check digit. By running the algorithm, and comparing the check digit you get from the algorithm with the check digit encoded with the credit card number, you can verify that you have correctly read all of the digits and that they make a valid combination. Possible uses for this information:  When a user has keyed in a credit card number (or scanned it) and you want to validate it before sending it our for debit authorization.  When issuing cards, say an affinity card, you might want to add a check digit using the MOD 10 method. 2.1. Prefix, Length, and Check Digit Criteria Here is a table outlining the major credit cards that you might want to validate. CARD TYPE Prefix Length Check digit Algorithm MASTERCARD 51-55 16 mod 10 VISA 4 13, 16 mod 10 34 AMEX 15 mod 10 37 300-305 Diners Club/ Carte Blanche 36 14 mod 10 38 Discover 6011 16 mod 10 2014 enRoute 15 any 2149 JCB 3 16 mod 10 2131 JCB 15 mod 10 1800 Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 6
7. 7. Các tài liệu về thuật toán Luhn 2008 2.2. LUHN Formula (Mod 10) for Validation of Primary Account Number The following steps are required to validate the primary account number: Step 1: Double the value of alternate digits of the primary account number beginning with the second digit from the right (the first right--hand digit is the check digit.) Step 2: Add the individual digits comprising the products obtained in Step 1 to each of the unaffected digits in the original number. Step 3: The total obtained in Step 2 must be a number ending in zero (30, 40, 50, etc.) for the account number to be validated. For example, to validate the primary account number 49927398716: Step 1: 49927398716 x2 x2 x2 x2 x2 ------------------------------ 18 4 6 16 2 Step 2: 4 +(1+8)+ 9 + (4) + 7 + (6) + 9 +(1+6) + 7 + (2) + 6 Step 3: Sum = 70 : Card number is validated Note: Card is valid because the 70/10 yields no remainder. The great folks at ICVERIFY are the original source of this data, I only formatted it in HTML. If you are in the market, I wrote a set of FoxPro modules for Windows/Dos that interface nicely with ICVERIFY in a multi-user LAN setup. You just set up ICVERIFY on a single station, and all stations on the LAN can authorize credit cards with a single FOXBASE function call. Of course, you have to license ICVERIFY by the node, but it is very reasonable. I also wrote a couple of simple functions to perform pre-authorization, card screening, etc. Here is a Microsoft Excel worksheet that will validate a number for you (useful for understanding the algorithm, it is in a .ZIP compressed format) Horace Vallas made a NeoWebScript (Tcl really) procedure that implements it. Check it out at https://enterprise.neosoft.com/secureforms/hav/ Because I get at least a letter a week regarding this routine, here are some additional helpful notes: Make sure that you: Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 7
8. 8. Các tài liệu về thuật toán Luhn 2008 1. have started with the rightmost digit (including the check digit) (figure odd and even based upon the rightmost digit being odd, regardless of the length of the Credit Card.) ALWAYS work right to left. 2. the check digit counts as digit #1 (assuming that the rightmost digit is the check digit) and is not doubled 3. double every second digit (starting with digit # 2 from the right) 4. remember that when you double a number over 4, (6 for example) you dont add the result to your total, but rather the sum of the digits of the result (in the above example 6*2=12 so you would add 1+2 to your total (not 12). 5. always include the Visa or M/C/ prefix. Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 8
9. 9. Các tài liệu về thuật toán Luhn 2008 3. How To Generate *Valid* Credit Card Numbers What do the credit card numbers mean and how are they generated? I need to start with a disclaimer: Do not use any credit card numbers, except your own, to buy things off internet. It’s wrong and it’s illegal. The purpose of this post is *not* to create fraudulent workable card numbers. It is to explain the math and the science behind those numbers that most of us see day in and day out; and hence this post should be viewed from a purely academic perspective. 3.1. Typical credit card anatomy Before we understand how credit card numbers are generated, here is a brief explanation of what a typical credit card number means.  Out of the 16 numbers on a typical credit card, the set of first 6 digits is known as the issuer identifier number (read this for details), and the last digit is known as the “check digit” which is generated in such a way as to satisfy a certain condition (the Luhn or Mod 10 check). “Luhn check” is explained later in this post. The term sounds intimidating, but it’s really a very simple (and elegant) concept.  Taking away the 6 identifier digits and 1 check digit leaves us with 9 digits in the middle that form the “account number”.  Now, there are 10 possible numbers (from 0 to 9) that can be arranged in these 9 places. This gives rise to 109 combinations, that is, 1 billion possible account numbers (per issuer identifier).  With each account number, there is always an unique check digit associated (for a given issuer identifier and an account number, there cannot be more than one correct check digit)  Amex issues credit cards with15 digits. The account numbers in this case are 8 digit long. Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 9
10. 10. Các tài liệu về thuật toán Luhn 2008 3.2. What is the “Luhn” or “Mod 10″ check? In 1954, Hans Luhn of IBM proposed an algorithm to be used as a validity criterion for a given set of numbers. Almost all credit card numbers are generated following this validity criterion…also called as the Luhn check or the Mod 10 check. It goes without saying that the Luhn check is also used to verify a given existing card number. If a credit card number does not satisfy this check, it is not a valid number. For a 16 digit credit card number, the Luhn check can be described as follows: 1. Starting with the check digit, double the value of every second digit (never double the check digit). For example, in a 16 digit credit card number, double the 15th, 13th, 11th, 9th…digits (digits in odd places). In all, you will need to double eight digits. 2. If doubling of a number results in a two digit number, add up the digits to get a single digit number. This will result in eight single digit numbers. 3. Now, replace the digits in the odd places (in the original credit card number) with these new single digit numbers to get a new 16 digit number. 4. Add up all the digits in this new number. If the final total is perfectly divisible by 10, then the credit card number is valid (Luhn check is satisfied), else it is invalid. When credit card numbers are generated, the same steps are followed with one minor change. First, the issuer identifier and account numbers are assigned (issuer numbers are fixed for a given financial institution, whereas the account numbers are randomly allocated - I think). Then, the check digit is assumed to be some variable, say X. After this, the above steps are followed, and during the last step, X is chosen in such a way that it satisfies the Luhn check. This part is a bit confusing and takes some time to understand. However, don’t get stuck here…continue reading through the examples below and you will figure out what this is all about. 3.3. Credit card numbers valid or invalid? Have you ever wondered if those numbers on the fake plastic or cardboard credit cards that come with the “preapproved” offers are real or imaginary? If they are not valid, how do you know it?…Just apply the Luhn check and all the those fake credit cards will invariably fail.Here is an example of a VISA credit card (look at the expiry date - 01/09 ..it’s still valid ! ) Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 10
11. 11. Các tài liệu về thuật toán Luhn 2008 Note that the credit card number starts with “4″…so it is indeed a VISA issued credit card (VISA cards start with “4″ and MasterCard/Maestro cards start with “5″). Now, let us apply the Luhn algorithm to this card. To make it easier on you guys, I have created a schematic of the steps towards the Luhn check (below) for this card number 4552 7204 1234 5678:  In this case, when we sum up the total, it comes to 61 which is not perfectly divisible by 10, and hence this credit card number is invalid.  If such a credit card number is ever generated, the value of the check digit would be adjusted in such a way as to satisfy the Luhn condition. In this case, the only value of the check digit, that will create a valid credit card number, is 7. Choosing 7 as the check digit will bring the total to 60 (which is perfectly divisible by 10) and the Luhn condition will be satisfied. So the valid credit card number will be 4552 7204 1234 5677. Let’s try another example, this time with a MasterCard. Again, performing the Luhn check on this credit card number, we have: Chuyên đề Thương Mại điện tử - Bộ môn Hệ thống thông tin – Khoa Công nghệ thông tin Page 11