Which algorithm does CreditCardAttribute use for credit card number format validation

送分小仙女□ 提交于 2019-12-07 10:12:43

问题


.NET 4.5 includes a new validation attribute named as CreditCardAttribute and this attribute specifies that a data field value is a credit card number. When I decompile the assembly which contains this class, I can see the following code for the credit card number validation:

public override bool IsValid(object value)
{
  if (value == null)
  {
    return true;
  }
  string text = value as string;
  if (text == null)
  {
    return false;
  }
  text = text.Replace("-", "");
  text = text.Replace(" ", "");
  int num = 0;
  bool flag = false;
  foreach (char current in text.Reverse<char>())
  {
    if (current < '0' || current > '9')
    {
      return false;
    }
    int i = (int)((current - '0') * (flag ? '\u0002' : '\u0001'));
    flag = !flag;
    while (i > 0)
    {
      num += i % 10;
      i /= 10;
    }
  }
  return num % 10 == 0;
}

Does anybody know which algorithm is applied here to validate the number format? Luhn's algorithm? Also, is this an ISO standard? Finally, do you think that this is the right and 100% correct implementation?

MSDN doesn't provide much information about this. In fact, they have the wrong information as below:

Remarks

The value is validated using a regular expression. The class does not validate that the credit card number is valid for purchases, only that it is well formed.


回答1:


The last line:

return num % 10 == 0;

Is a very strong hint that this is a Luhn Algorithm




回答2:


This algorithm is really a Luhn's algorithm. Unfortunately not all card numbers could be verified by this algorithm so it is not 100% method. However, card numbers of Mastercard and Visa products that allow keyed card number entry should pass this check.

The only 100% way to validate if the card number exist is to perform a transaction. Usually Acquirer Host System protocols used for PoS connections have provisions to validate if the card is not on stop lists and exist in routing tables.



来源:https://stackoverflow.com/questions/12580450/which-algorithm-does-creditcardattribute-use-for-credit-card-number-format-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!