File: credit_card_number_validation.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (323 lines) | stat: -rw-r--r-- 10,824 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/common/credit_card_number_validation.h"

#include <stddef.h>

#include <string>
#include <string_view>

#include "base/containers/adapters.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "components/autofill/core/common/autofill_regexes.h"
#include "components/autofill/core/common/credit_card_network_identifiers.h"

namespace autofill {

namespace {

constexpr char16_t kWhiteSpaceSeparator = ' ';

constexpr auto k15DigitAmexNumberSegmentations = std::to_array({4, 6, 5});
constexpr auto k16DigitNumberSegmentations = std::to_array({4, 4, 4, 4});

// Returns a new string based on the input `number` by adding a white space
// between `segments`. The provided `segments` denotes the length of each
// segment, and we don't need to add whitespace to the last segmentation. For
// example, if you would like to format 15-digit card number into "XXXX XXXXXX
// XXXXX", you need to provide [4, 6, 5] as the `segments`.
std::u16string AddWhiteSpaceSeparatorForNumber(std::u16string_view number,
                                               base::span<const int> segments) {
  std::u16string formatted;
  int pos = 0;
  for (int segment : segments) {
    formatted += number.substr(pos, segment);
    formatted += kWhiteSpaceSeparator;
    pos += segment;
  }

  // Remove the extra white space at the end.
  return formatted.substr(0, formatted.length() - 1);
}

}  // namespace

bool IsValidCreditCardNumber(std::u16string_view text) {
  const std::u16string number = StripCardNumberSeparators(text);
  return HasCorrectCreditCardNumberLength(number) && PassesLuhnCheck(number);
}

bool HasCorrectCreditCardNumberLength(std::u16string_view number) {
  // Credit card numbers are at most 19 digits in length, 12 digits seems to
  // be a fairly safe lower-bound [1].  Specific card issuers have more rigidly
  // defined sizes.
  // (Last updated: May 29, 2017)
  // [1] https://en.wikipedia.org/wiki/Payment_card_number.
  // CardEditor.isCardNumberLengthMaxium() needs to be kept in sync.
  const char* const type = GetCardNetwork(number);
  if (type == kAmericanExpressCard && number.size() != 15)
    return false;
  if (type == kDinersCard && number.size() != 14)
    return false;
  if (type == kDiscoverCard && number.size() != 16)
    return false;
  if (type == kEloCard && number.size() != 16)
    return false;
  if (type == kJCBCard && number.size() != 16)
    return false;
  if (type == kMasterCard && number.size() != 16)
    return false;
  if (type == kMirCard && number.size() != 16)
    return false;
  if (type == kTroyCard && number.size() != 16)
    return false;
  if (type == kUnionPay && (number.size() < 16 || number.size() > 19))
    return false;
  if (type == kVerveCard && number.size() != 16 && number.size() != 18 &&
      number.size() != 19)
    return false;
  if (type == kVisaCard && number.size() != 13 && number.size() != 16 &&
      number.size() != 19)
    return false;
  if (type == kGenericCard && (number.size() < 12 || number.size() > 19))
    return false;

  return true;
}

bool PassesLuhnCheck(std::u16string_view number) {
  // Use the Luhn formula [3] to validate the number.
  // [3] http://en.wikipedia.org/wiki/Luhn_algorithm
  int sum = 0;
  bool odd = false;
  for (char16_t c : base::Reversed(number)) {
    if (!base::IsAsciiDigit(c))
      return false;

    int digit = c - '0';
    if (odd) {
      digit *= 2;
      sum += digit / 10 + digit % 10;
    } else {
      sum += digit;
    }
    odd = !odd;
  }

  return (sum % 10) == 0;
}

std::u16string StripCardNumberSeparators(std::u16string_view number) {
  std::u16string stripped;
  base::RemoveChars(number, u"- ", &stripped);
  return stripped;
}

const char* GetCardNetwork(std::u16string_view number) {
  // Credit card number specifications taken from:
  // https://en.wikipedia.org/wiki/Payment_card_number,
  // http://www.regular-expressions.info/creditcard.html,
  // https://developer.ean.com/general-info/valid-card-types,
  // http://www.bincodes.com/, and
  // http://www.fraudpractice.com/FL-binCC.html.
  // (Last updated: March 2021; change Troy bin range)
  //
  // Card Type              Prefix(es)                                  Length
  // --------------------------------------------------------------------------
  // Visa                   4                                          13,16,19
  // American Express       34,37                                      15
  // Diners Club            300-305,309,36,38-39                       14
  // Discover Card          6011,644-649,65                            16
  // Elo                    See Elo regex pattern below                16
  // JCB                    3528-3589                                  16
  // Mastercard             2221-2720, 51-55                           16
  // MIR                    2200-2204                                  16
  // Troy                   22050-22052, 9792                          16
  // UnionPay               62                                         16-19
  // Verve                  506099–506198,507865-507964,650002–650027  16,18,19

  // Determine the network for the given |number| by going from the longest
  // (most specific) prefix to the shortest (most general) prefix.
  std::u16string stripped_number = StripCardNumberSeparators(number);

  // Original Elo parsing included only 6 BIN prefixes. This regex pattern,
  // sourced from the official Elo documentation, attempts to cover missing gaps
  // via a more comprehensive solution.
  static constexpr char16_t kEloRegexPattern[] =
      // clang-format off
    u"^("
      u"50("
        u"67("
          u"0[78]|"
          u"1[5789]|"
          u"2[012456789]|"
          u"3[01234569]|"
          u"4[0-7]|"
          u"53|"
          u"7[4-8]"
        u")|"
        u"9("
          u"0(0[0-9]|1[34]|2[013457]|3[0359]|4[0123568]|5[01456789]|6[012356789]|7[013]|8[123789]|9[1379])|"
          u"1(0[34568]|4[6-9]|5[1245678]|8[36789])|"
          u"2(2[02]|57|6[0-9]|7[1245689]|8[023456789]|9[1-6])|"
          u"3(0[78]|5[78])|"
          u"4(0[7-9]|1[012456789]|2[02]|5[7-9]|6[0-5]|8[45])|"
          u"55[01]|"
          u"636|"
          u"7(2[3-8]|32|6[5-9])"
        u")"
      u")|"
      u"4("
        u"0117[89]|3(1274|8935)|5(1416|7(393|63[12]))"
      u")|"
      u"6("
        u"27780|"
        u"36368|"
        u"5("
          u"0("
            u"0(3[1258]|4[026]|69|7[0178])|"
            u"4(0[67]|1[0-3]|2[2345689]|3[0568]|8[5-9]|9[0-9])|"
            u"5(0[01346789]|1[01246789]|2[0-9]|3[0178]|5[2-9]|6[012356789]|7[01789]|8[0134679]|9[0-8])|"
            u"72[0-7]|"
            u"9(0[1-9]|1[0-9]|2[0128]|3[89]|4[6-9]|5[01578]|6[2-9]|7[01])"
          u")|"
          u"16("
            u"5[236789]|"
            u"6[025678]|"
            u"7[013456789]|"
            u"88"
          u")|"
          u"50("
            u"0[01356789]|"
            u"1[2568]|"
            u"26|"
            u"3[6-8]|"
            u"5[1267]"
          u")"
        u")"
      u")"
    u")$";
  // clang-format on

  // Check for prefixes of length 6.
  if (stripped_number.size() >= 6) {
    int first_six_digits = 0;
    if (!base::StringToInt(stripped_number.substr(0, 6), &first_six_digits))
      return kGenericCard;

    if (MatchesRegex<kEloRegexPattern>(
            base::NumberToString16(first_six_digits))) {
      return kEloCard;
    }

    if ((first_six_digits >= 506099 && first_six_digits <= 506198) ||
        (first_six_digits >= 507865 && first_six_digits <= 507964) ||
        (first_six_digits >= 650002 && first_six_digits <= 650027)) {
      return kVerveCard;
    }
  }

  // Check for prefixes of length 5.
  if (stripped_number.size() >= 5) {
    int first_five_digits = 0;
    if (!base::StringToInt(stripped_number.substr(0, 5), &first_five_digits))
      return kGenericCard;

    if (first_five_digits == 22050 || first_five_digits == 22051 ||
        first_five_digits == 22052) {
      return kTroyCard;
    }
  }

  // Check for prefixes of length 4.
  if (stripped_number.size() >= 4) {
    int first_four_digits = 0;
    if (!base::StringToInt(stripped_number.substr(0, 4), &first_four_digits))
      return kGenericCard;

    if (first_four_digits >= 2200 && first_four_digits <= 2204)
      return kMirCard;

    if (first_four_digits == 9792)
      return kTroyCard;

    if (first_four_digits >= 2221 && first_four_digits <= 2720)
      return kMasterCard;

    if (first_four_digits >= 3528 && first_four_digits <= 3589)
      return kJCBCard;

    if (first_four_digits == 6011)
      return kDiscoverCard;
  }

  // Check for prefixes of length 3.
  if (stripped_number.size() >= 3) {
    int first_three_digits = 0;
    if (!base::StringToInt(stripped_number.substr(0, 3), &first_three_digits))
      return kGenericCard;

    if ((first_three_digits >= 300 && first_three_digits <= 305) ||
        first_three_digits == 309)
      return kDinersCard;

    if (first_three_digits >= 644 && first_three_digits <= 649)
      return kDiscoverCard;
  }

  // Check for prefixes of length 2.
  if (stripped_number.size() >= 2) {
    int first_two_digits = 0;
    if (!base::StringToInt(stripped_number.substr(0, 2), &first_two_digits))
      return kGenericCard;

    if (first_two_digits == 34 || first_two_digits == 37)
      return kAmericanExpressCard;

    if (first_two_digits == 36 || first_two_digits == 38 ||
        first_two_digits == 39)
      return kDinersCard;

    if (first_two_digits >= 51 && first_two_digits <= 55)
      return kMasterCard;

    if (first_two_digits == 62)
      return kUnionPay;

    if (first_two_digits == 65)
      return kDiscoverCard;
  }

  // Check for prefixes of length 1.
  if (stripped_number.empty())
    return kGenericCard;

  if (stripped_number[0] == '4')
    return kVisaCard;

  return kGenericCard;
}

std::u16string GetFormattedCardNumberForDisplay(std::u16string_view number) {
  std::u16string stripped = StripCardNumberSeparators(number);
  if (stripped.size() == 16) {
    return AddWhiteSpaceSeparatorForNumber(stripped,
                                           k16DigitNumberSegmentations);
  }
  if (stripped.size() == 15 &&
      GetCardNetwork(stripped) == kAmericanExpressCard) {
    return AddWhiteSpaceSeparatorForNumber(stripped,
                                           k15DigitAmexNumberSegmentations);
  }

  return std::u16string(number);
}

}  // namespace autofill