SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
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
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
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
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
Các tài liệu về thuật toán Luhn                                                              2008

            if(modulo > 0)
            {
              digits[length-1] = 10 - modulo;
            }
            // No else req'd - 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
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
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
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 don't 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
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
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
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
Các tài liệu về thuật toán Luhn                                                                    2008




             The total comes to 65 which is not perfectly divisible by 10. Hence this credit card
              number is invalid.
             In this case, a valid credit card number will result only if the check digit is 8. This will
              bring the total to 70 which is perfectly divisible by 10. So the valid credit card number will
              be 5490 1234 5678 9128.

          3.4.    Closing remarks

       If I still have your attention, here are some additional thoughts. In the context of this post, by the
       term “valid”, I mean “mathematically valid”. A mathematically valid credit card does not mean a
       “working” credit card. The Luhn formula validates only the credit card number; it does not
       validate the expiry date and/or card security code (CVV, CVC). Plus, as discussed before, the 9
       digit account number will yield 1 billion combinations; so the chances of getting a working credit
       card number are very remote. It should also be noted that, this validation is usually employed at
       the transaction end; which means that numbers that do not satisfy the Luhn check are not
       forwarded to the card issuer and the transaction is terminated. If you have a fake credit card
       which satisfies the Luhn check, it will go through at the transaction end, but the card issuer will
       most likely catch the mischief. So don’t go about trying to use these numbers to buy stuff.

       Just to be clear on this, I don’t expect comments like these (check out the source of this
       comment):

       hey. im hearing good things about your site! i need some money to jump start my poker career.
       Probably about 40-100$ would do. i dont have a credit card to use and it pisses me off because
       i know i could beat the majority of the people online. please help

       If you intend to post such comments, at least be extremely funny.

       So you think you can separate out valid and invalid account numbers now? Here are a couple of
       trial numbers for you:

             5491 9469 1544 4923 - Valid or invalid? If invalid, what should have been the correct
              check digit to make it valid?
             4539 9920 4349 1562 - Valid or invalid? If invalid, what should have been the correct
              check digit to make it valid?

       Sudoku fans will quickly figure out multiple valid combinations of the above numbers. If you
       don’t want to do the math, here are some ready made valid (”test”) credit card numbers from
       Paypal.By the way, the Luhn check is also valid for debit card numbers.I am still in the learning
       phase with this topic and trying to further understand how people use (or misuse (?)) such
       information. If you have some insight in this matter, please feel free to share it with us.If 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 12
Các tài liệu về thuật toán Luhn                                                               2008

       liked what you read above, go ahead and subscribe to this blog to get more updates. It’s easy -
       just click on one of the buttons below and get the feed.

          3.5.    Resources and References

       There is a vast amount of literature on the Luhn algorithm and a quick Google search will
       enlighten you on how popular this topic is. If you don’t want to read all that, here are links to
       some interesting reading.

             Card Identification Features (pdf file) - extremely useful, must read.
             Credit Card Numbers and Credit Card Generator @ Graham King.
             Anatomy of Credit Card Numbers.
             Credit Card Number - Wikipedia.




       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 13
Các tài liệu về thuật toán Luhn                                                                      2008

           4. Actionscript Credit Card Validation - Luhn Check
       By no means did I write this, if you do a search for Luhn Check in google you will come with a million
       results. However, most of them are Java implementations, JavaScript, ASP, JSP, but never ActionScript.
       Below is a version I converted from Javascript into Actionscript 2.0. This Luhn Check validates the users
       credit card numbers and makes sure A) there are enough for the given card, and B) matches the number
       pattern of a given card. This example only checks Visa, MasterCard, American Express, and Diners Club.

       BY NO MEANS IS THIS THE ONLY CHECK YOU NEED TO DO TO PROCESS AN
       ORDER.

       You must use a valid payment gateway that does proper server side credit card validation. The
       purpose of this script is to reduce traffic to the server by weeding out the invalid credit card
       numbers. If the client side tests are successful the application then has to send the Credit Card
       information to the server for proper Credit Card Validation and order processing.

       lass com.scottgmorgan.utils.CreditCardValidation {

           /**
           * checks for datein the format MM/YY or MM/YYYY against the current date
           * @param month a number representing the month to be validated against.
           * @param year a number representing the year to be validated against.
           */
           public function isValidExpDate(month:Number,year:Number):Boolean {
               var result:Boolean = true;
               var now:Date = new Date();
               var nowMonth:Number = now.getMonth() + 1;
               var nowYear:Number = now.getFullYear();
               if ((nowYear > year) || ((nowYear == year ) && (nowMonth > month))){
                  result = false;
               }

               return result;
           }

          /**
          * checks for valid credit card format using the Luhn check and known digit
          * about various cards
          * @ccType a string indicating the entered credit card name
          * @ccNum a string indicating the credit card number being used.
          */
          public function
       isValidCreditCardNumber(ccType:String,ccNum:String):Boolean {
              var result:Boolean = true;
              if (ccNum.length>0){
                 if (isNaN(ccNum)){
                    result = false;
                 }
                 if (result){
                    if (!luhnCheck(ccNum) || !validateCCNum(ccType,ccNum)){
                       result = false;
                    }
                 }

       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 14
Các tài liệu về thuật toán Luhn                                                              2008

               }
               return result;
          }

          private function luhnCheck(str:String){
             var result:Boolean = true;
             var sum:Number = 0;
             var mul:Number = 1;
             var strLen:Number = str.length;
             for (var i:Number = 0; i < strLen; i++){
                var digit:String = str.substring(strLen-i-1,strLen-i);
                var tproduct:Number = parseInt(digit ,10)*mul;
                if (tproduct >= 10){
                   sum += (tproduct % 10) + 1;
                } else {
                    sum += tproduct;
                }

                   if (mul == 1){
                      mul++;
                   } else {
                      mul--;
                   }
               }

               if ((sum % 10) != 0){
                  result = false;
               }

               return result;
          }

          private function validateCCNum(cardType:String,cardNum:String):Boolean{
             var result:Boolean = false;
             cardType = cardType.toUpperCase();
             var cardLen:Number = cardNum.length;
             var firstdig:String = cardNum.substring(0,1);
             var seconddig:String = cardNum.substring(1,2);
             var first4digs:String = cardNum.substring(0,4);

               switch (cardType){
                  case "VISA":
                     result = ((cardLen == 16) || (cardLen == 13)) && (firstdig ==
       "4");
                   break;
                case "AMEX":
                   var validNums = "47";
                   result = (cardLen == 15) && (firstdig == "3") &&
       (validNums.indexOf(seconddig)>=0);
                   break;
                case "MASTERCARD":
                   var validNums = "12345";
                   result = (cardLen == 16) && (firstdig == "5") &&
       (validNums.indexOf(seconddig)>=0);
                   break;
                case "DISCOVER":
                   result = (cardLen == 16) && (first4digs == "6011");

       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 15
Các tài liệu về thuật toán Luhn                                                                2008

                   break;
                case "DINERS":
                   var validNums = "068";
                   result = (cardLen == 14) && (firstdig == "3") &&
       (validNums.indexOf(seconddig)>=0);
                   break;
                }
             return result;
          }
       }

       And here is the sample code that instantiates this bad boy:

       var ccValidator = new CreditCardValidation();
       var valid = ccValidator.isValidCreditCardNumber('visa', '4111111111111111');

       trace('card is valid: ' + valid);

       Pretty straightforward. I have hardcoded the values in the method call above but in the real world
       this would be puuled from a textfield or a combo box for the card type.

       As a side note, if you ever want to get around the validation for Visa simply enter
       „4111111111111111′ (1 “4″, and 15 “1‟s”). Unfortunatly, this number will not get you past the
       real creditcard validation that occurs on the server or at the payment gateway.




       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 16

Weitere ähnliche Inhalte

Was ist angesagt?

Emily Stamm - Post-Quantum Cryptography
Emily Stamm - Post-Quantum CryptographyEmily Stamm - Post-Quantum Cryptography
Emily Stamm - Post-Quantum CryptographyCSNP
 
Divide and Conquer Case Study
Divide and Conquer Case StudyDivide and Conquer Case Study
Divide and Conquer Case StudyKushagraChadha1
 
PBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android ApplicationsPBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android ApplicationsShiv Sahni
 
Fermat and euler theorem
Fermat and euler theoremFermat and euler theorem
Fermat and euler theoremJanani S
 
Cryptography and Information Security
Cryptography and Information SecurityCryptography and Information Security
Cryptography and Information SecurityDr Naim R Kidwai
 
RSA Algorithm - Public Key Cryptography
RSA Algorithm - Public Key CryptographyRSA Algorithm - Public Key Cryptography
RSA Algorithm - Public Key CryptographyMd. Shafiul Alam Sagor
 
Elliptic Curve Cryptography
Elliptic Curve CryptographyElliptic Curve Cryptography
Elliptic Curve CryptographyKelly Bresnahan
 
Estructura lógica de las computadoras
Estructura lógica de las computadorasEstructura lógica de las computadoras
Estructura lógica de las computadorasLaura Treviño
 
Discrete Mathematics Lecture
Discrete Mathematics LectureDiscrete Mathematics Lecture
Discrete Mathematics LectureGenie Rose Santos
 
Cryptography - A Brief History
Cryptography - A Brief HistoryCryptography - A Brief History
Cryptography - A Brief Historyprasenjeetd
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit iArthyR3
 

Was ist angesagt? (20)

Blind Signature Scheme
Blind Signature SchemeBlind Signature Scheme
Blind Signature Scheme
 
Cryptography and Network security # Lecture 4
Cryptography and Network security # Lecture 4Cryptography and Network security # Lecture 4
Cryptography and Network security # Lecture 4
 
Emily Stamm - Post-Quantum Cryptography
Emily Stamm - Post-Quantum CryptographyEmily Stamm - Post-Quantum Cryptography
Emily Stamm - Post-Quantum Cryptography
 
Divide and Conquer Case Study
Divide and Conquer Case StudyDivide and Conquer Case Study
Divide and Conquer Case Study
 
Kruskal's algorithm
Kruskal's algorithmKruskal's algorithm
Kruskal's algorithm
 
Arboles decision id3
Arboles decision   id3Arboles decision   id3
Arboles decision id3
 
PBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android ApplicationsPBKDF2: Storing Sensitive Data Securely in Android Applications
PBKDF2: Storing Sensitive Data Securely in Android Applications
 
Fermat and euler theorem
Fermat and euler theoremFermat and euler theorem
Fermat and euler theorem
 
Cryptography and Information Security
Cryptography and Information SecurityCryptography and Information Security
Cryptography and Information Security
 
Applied Cryptography
Applied CryptographyApplied Cryptography
Applied Cryptography
 
RSA Algorithm - Public Key Cryptography
RSA Algorithm - Public Key CryptographyRSA Algorithm - Public Key Cryptography
RSA Algorithm - Public Key Cryptography
 
Elgamal
ElgamalElgamal
Elgamal
 
Elliptic Curve Cryptography
Elliptic Curve CryptographyElliptic Curve Cryptography
Elliptic Curve Cryptography
 
Estructura lógica de las computadoras
Estructura lógica de las computadorasEstructura lógica de las computadoras
Estructura lógica de las computadoras
 
Network security Topic 2 overview continued
Network security Topic 2 overview continuedNetwork security Topic 2 overview continued
Network security Topic 2 overview continued
 
Programmation Java
Programmation JavaProgrammation Java
Programmation Java
 
Daa notes 3
Daa notes 3Daa notes 3
Daa notes 3
 
Discrete Mathematics Lecture
Discrete Mathematics LectureDiscrete Mathematics Lecture
Discrete Mathematics Lecture
 
Cryptography - A Brief History
Cryptography - A Brief HistoryCryptography - A Brief History
Cryptography - A Brief History
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 

Ähnlich wie Luhn algorithm

Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithmK Hari Shankar
 
Binary Mathematics Classwork and Hw
Binary Mathematics Classwork and HwBinary Mathematics Classwork and Hw
Binary Mathematics Classwork and HwJoji Thompson
 
2s complement arithmetic
2s complement arithmetic2s complement arithmetic
2s complement arithmeticSanjay Saluth
 
2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt2sComplementArithmetic1.ppt
2sComplementArithmetic1.pptSathishkumar.V
 
2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt2sComplementArithmetic1.ppt
2sComplementArithmetic1.pptMeghadriGhosh4
 
2sComplementArithmetic1 lecture slides ppt
2sComplementArithmetic1 lecture slides ppt2sComplementArithmetic1 lecture slides ppt
2sComplementArithmetic1 lecture slides pptnashitahalwaz95
 
21EC201– Digital Principles and system design.pptx
21EC201– Digital Principles and system design.pptx21EC201– Digital Principles and system design.pptx
21EC201– Digital Principles and system design.pptxGobinathAECEJRF1101
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Number system(everyday41.com).pdf
Number system(everyday41.com).pdfNumber system(everyday41.com).pdf
Number system(everyday41.com).pdfeveryday
 
Number systems and conversions
Number systems and conversionsNumber systems and conversions
Number systems and conversionsSusantha Herath
 
Reliable multimedia transmission under noisy condition
Reliable multimedia transmission under noisy conditionReliable multimedia transmission under noisy condition
Reliable multimedia transmission under noisy conditionShahrukh Ali Khan
 
Chapter 1 digital design.pptx
Chapter 1 digital design.pptxChapter 1 digital design.pptx
Chapter 1 digital design.pptxAliaaTarek5
 
More on number system
More on number systemMore on number system
More on number systemsamina khan
 

Ähnlich wie Luhn algorithm (20)

Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 
Complement
ComplementComplement
Complement
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Binary Mathematics Classwork and Hw
Binary Mathematics Classwork and HwBinary Mathematics Classwork and Hw
Binary Mathematics Classwork and Hw
 
2s complement arithmetic
2s complement arithmetic2s complement arithmetic
2s complement arithmetic
 
2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt
 
2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt2sComplementArithmetic1.ppt
2sComplementArithmetic1.ppt
 
2sComplementArithmetic1 lecture slides ppt
2sComplementArithmetic1 lecture slides ppt2sComplementArithmetic1 lecture slides ppt
2sComplementArithmetic1 lecture slides ppt
 
21EC201– Digital Principles and system design.pptx
21EC201– Digital Principles and system design.pptx21EC201– Digital Principles and system design.pptx
21EC201– Digital Principles and system design.pptx
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Number system(everyday41.com).pdf
Number system(everyday41.com).pdfNumber system(everyday41.com).pdf
Number system(everyday41.com).pdf
 
Number systems and conversions
Number systems and conversionsNumber systems and conversions
Number systems and conversions
 
Reliable multimedia transmission under noisy condition
Reliable multimedia transmission under noisy conditionReliable multimedia transmission under noisy condition
Reliable multimedia transmission under noisy condition
 
Chapter 1 digital design.pptx
Chapter 1 digital design.pptxChapter 1 digital design.pptx
Chapter 1 digital design.pptx
 
Chapter 1: Binary System
 Chapter 1: Binary System Chapter 1: Binary System
Chapter 1: Binary System
 
More on number system
More on number systemMore on number system
More on number system
 
Number System
Number SystemNumber System
Number System
 
Basics of digital electronics
Basics of digital electronicsBasics of digital electronics
Basics of digital electronics
 
Alu1
Alu1Alu1
Alu1
 
Number Systems
Number  SystemsNumber  Systems
Number Systems
 

Kürzlich hochgeladen

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 

Kürzlich hochgeladen (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

Luhn algorithm

  • 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. 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. 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. 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. Các tài liệu về thuật toán Luhn 2008 if(modulo > 0) { digits[length-1] = 10 - modulo; } // No else req'd - 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. 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. 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. 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 don't 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. 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. 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. 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
  • 12. Các tài liệu về thuật toán Luhn 2008  The total comes to 65 which is not perfectly divisible by 10. Hence this credit card number is invalid.  In this case, a valid credit card number will result only if the check digit is 8. This will bring the total to 70 which is perfectly divisible by 10. So the valid credit card number will be 5490 1234 5678 9128. 3.4. Closing remarks If I still have your attention, here are some additional thoughts. In the context of this post, by the term “valid”, I mean “mathematically valid”. A mathematically valid credit card does not mean a “working” credit card. The Luhn formula validates only the credit card number; it does not validate the expiry date and/or card security code (CVV, CVC). Plus, as discussed before, the 9 digit account number will yield 1 billion combinations; so the chances of getting a working credit card number are very remote. It should also be noted that, this validation is usually employed at the transaction end; which means that numbers that do not satisfy the Luhn check are not forwarded to the card issuer and the transaction is terminated. If you have a fake credit card which satisfies the Luhn check, it will go through at the transaction end, but the card issuer will most likely catch the mischief. So don’t go about trying to use these numbers to buy stuff. Just to be clear on this, I don’t expect comments like these (check out the source of this comment): hey. im hearing good things about your site! i need some money to jump start my poker career. Probably about 40-100$ would do. i dont have a credit card to use and it pisses me off because i know i could beat the majority of the people online. please help If you intend to post such comments, at least be extremely funny. So you think you can separate out valid and invalid account numbers now? Here are a couple of trial numbers for you:  5491 9469 1544 4923 - Valid or invalid? If invalid, what should have been the correct check digit to make it valid?  4539 9920 4349 1562 - Valid or invalid? If invalid, what should have been the correct check digit to make it valid? Sudoku fans will quickly figure out multiple valid combinations of the above numbers. If you don’t want to do the math, here are some ready made valid (”test”) credit card numbers from Paypal.By the way, the Luhn check is also valid for debit card numbers.I am still in the learning phase with this topic and trying to further understand how people use (or misuse (?)) such information. If you have some insight in this matter, please feel free to share it with us.If 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 12
  • 13. Các tài liệu về thuật toán Luhn 2008 liked what you read above, go ahead and subscribe to this blog to get more updates. It’s easy - just click on one of the buttons below and get the feed. 3.5. Resources and References There is a vast amount of literature on the Luhn algorithm and a quick Google search will enlighten you on how popular this topic is. If you don’t want to read all that, here are links to some interesting reading.  Card Identification Features (pdf file) - extremely useful, must read.  Credit Card Numbers and Credit Card Generator @ Graham King.  Anatomy of Credit Card Numbers.  Credit Card Number - Wikipedia. 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 13
  • 14. Các tài liệu về thuật toán Luhn 2008 4. Actionscript Credit Card Validation - Luhn Check By no means did I write this, if you do a search for Luhn Check in google you will come with a million results. However, most of them are Java implementations, JavaScript, ASP, JSP, but never ActionScript. Below is a version I converted from Javascript into Actionscript 2.0. This Luhn Check validates the users credit card numbers and makes sure A) there are enough for the given card, and B) matches the number pattern of a given card. This example only checks Visa, MasterCard, American Express, and Diners Club. BY NO MEANS IS THIS THE ONLY CHECK YOU NEED TO DO TO PROCESS AN ORDER. You must use a valid payment gateway that does proper server side credit card validation. The purpose of this script is to reduce traffic to the server by weeding out the invalid credit card numbers. If the client side tests are successful the application then has to send the Credit Card information to the server for proper Credit Card Validation and order processing. lass com.scottgmorgan.utils.CreditCardValidation { /** * checks for datein the format MM/YY or MM/YYYY against the current date * @param month a number representing the month to be validated against. * @param year a number representing the year to be validated against. */ public function isValidExpDate(month:Number,year:Number):Boolean { var result:Boolean = true; var now:Date = new Date(); var nowMonth:Number = now.getMonth() + 1; var nowYear:Number = now.getFullYear(); if ((nowYear > year) || ((nowYear == year ) && (nowMonth > month))){ result = false; } return result; } /** * checks for valid credit card format using the Luhn check and known digit * about various cards * @ccType a string indicating the entered credit card name * @ccNum a string indicating the credit card number being used. */ public function isValidCreditCardNumber(ccType:String,ccNum:String):Boolean { var result:Boolean = true; if (ccNum.length>0){ if (isNaN(ccNum)){ result = false; } if (result){ if (!luhnCheck(ccNum) || !validateCCNum(ccType,ccNum)){ result = false; } } 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 14
  • 15. Các tài liệu về thuật toán Luhn 2008 } return result; } private function luhnCheck(str:String){ var result:Boolean = true; var sum:Number = 0; var mul:Number = 1; var strLen:Number = str.length; for (var i:Number = 0; i < strLen; i++){ var digit:String = str.substring(strLen-i-1,strLen-i); var tproduct:Number = parseInt(digit ,10)*mul; if (tproduct >= 10){ sum += (tproduct % 10) + 1; } else { sum += tproduct; } if (mul == 1){ mul++; } else { mul--; } } if ((sum % 10) != 0){ result = false; } return result; } private function validateCCNum(cardType:String,cardNum:String):Boolean{ var result:Boolean = false; cardType = cardType.toUpperCase(); var cardLen:Number = cardNum.length; var firstdig:String = cardNum.substring(0,1); var seconddig:String = cardNum.substring(1,2); var first4digs:String = cardNum.substring(0,4); switch (cardType){ case "VISA": result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4"); break; case "AMEX": var validNums = "47"; result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0); break; case "MASTERCARD": var validNums = "12345"; result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0); break; case "DISCOVER": result = (cardLen == 16) && (first4digs == "6011"); 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 15
  • 16. Các tài liệu về thuật toán Luhn 2008 break; case "DINERS": var validNums = "068"; result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0); break; } return result; } } And here is the sample code that instantiates this bad boy: var ccValidator = new CreditCardValidation(); var valid = ccValidator.isValidCreditCardNumber('visa', '4111111111111111'); trace('card is valid: ' + valid); Pretty straightforward. I have hardcoded the values in the method call above but in the real world this would be puuled from a textfield or a combo box for the card type. As a side note, if you ever want to get around the validation for Visa simply enter „4111111111111111′ (1 “4″, and 15 “1‟s”). Unfortunatly, this number will not get you past the real creditcard validation that occurs on the server or at the payment gateway. 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 16