生成Luhn校验和

时间:2009-09-13 22:04:06

标签: php algorithm checksum check-digit luhn

有很多实现用于验证Luhn校验和但很少用于生成它们。我遇到了this one但是在我的测试中它发现它是错误的,我不理解delta变量背后的逻辑。

我已经创建了这个应该生成Luhn校验和的函数,但由于某些原因我还没有理解生成的校验和在一半时间内是无效的。

function Luhn($number, $iterations = 1)
{
    while ($iterations-- >= 1)
    {
        $stack = 0;
        $parity = strlen($number) % 2;
        $number = str_split($number, 1);

        foreach ($number as $key => $value)
        {
            if ($key % 2 == $parity)
            {
                $value *= 2;

                if ($value > 9)
                {
                    $value -= 9;
                }
            }

            $stack += $value;
        }

        $stack = 10 - $stack % 10;

        if ($stack == 10)
        {
            $stack = 0;
        }

        $number[] = $stack;
    }

    return implode('', $number);
}

一些例子:

Luhn(3); // 37, invalid
Luhn(37); // 372, valid
Luhn(372); // 3728, invalid
Luhn(3728); // 37283, valid
Luhn(37283); // 372837, invalid
Luhn(372837); // 3728375, valid

我正在验证生成的校验和against this page,我在这里做错了什么?


供将来参考,这是工作功能。

function Luhn($number, $iterations = 1)
{
    while ($iterations-- >= 1)
    {
        $stack = 0;
        $number = str_split(strrev($number), 1);

        foreach ($number as $key => $value)
        {
            if ($key % 2 == 0)
            {
                $value = array_sum(str_split($value * 2, 1));
            }

            $stack += $value;
        }

        $stack %= 10;

        if ($stack != 0)
        {
            $stack -= 10;
        }

        $number = implode('', array_reverse($number)) . abs($stack);
    }

    return $number;
}

我删除了$ parity变量,因为我们不需要它用于此目的,并验证:

function Luhn_Verify($number, $iterations = 1)
{
    $result = substr($number, 0, - $iterations);

    if (Luhn($result, $iterations) == $number)
    {
        return $result;
    }

    return false;
}

6 个答案:

答案 0 :(得分:8)

编辑:很抱歉,我现在已经意识到你已经有了几乎所有的答案,你只是错误地确定了哪个因素用于哪个数字。

现在我的整个答案可以用这句话总结:

你有一个因素反转,你将错误的数字乘以2取决于数字的长度。


查看Wikipedia article on the Luhn algorithm

你的校验和一半时间无效的原因是你的支票是你的号码有一个奇数位数的一半,然后你把错误的数字加倍。

对于37283,当从右边开始计算时,你得到这个数字序列:

  3 * 1 =  3             3
  8 * 2 = 16 --> 1 + 6 = 7
  2 * 1 =  2             2
  7 * 2 = 14 --> 1 + 4 = 5
+ 3 * 1 =  3             3
=                       20

该算法要求您对原始数字中的各个数字以及“右起每两位数字”的产品的各个数字求和。

所以从右边开始,你总计3 +(1 + 6)+ 2 +(1 + 4)+ 3,这样就可以得到20。

如果你最终得到的数字以0结尾,而20就是,则该数字有效。

现在,您的问题暗示您想知道如何生成校验和,嗯,这很简单,请执行以下操作:

  1. 多加零,所以你的号码从xyxyxyxy到xyxyxyxy0
  2. 计算新数字的luhn校验和总和
  3. 取总和,模数10,这样你就得到一个从0到10的单个数字
  4. 如果数字为0,那么祝贺你的校验和数字为零
  5. 否则,计算10位数以获得最后一位数而不是零
  6. 所需的数字

    示例:数字是12345

    1. Tack on the zero:123450
    2. 计算123450的luhn校验和,得到

      0   5    4    3    2    1
      1   2    1    2    1    2  <-- factor
      0   10   4    6    2    2  <-- product
      0  1 0   4    6    2    2  <-- sum these to: 0+1+0+4+6+2+2=15
      
    3. 取总和(15),模数10,得到5

    4. 数字(5),不为零
    5. 计算10-5,它给你5,最后一位应为5。
    6. 结果是123455。

答案 1 :(得分:3)

你的php是错误的,它导致无限循环。 这是我正在使用的工作版本,从您的代码中修改

  

函数Luhn($ number){

$stack = 0;
$number = str_split(strrev($number));

foreach ($number as $key => $value)
{
    if ($key % 2 == 0)
    {
        $value = array_sum(str_split($value * 2));
    }
    $stack += $value;
}
$stack %= 10;

if ($stack != 0)
{
    $stack -= 10;     $stack = abs($stack);
}


$number = implode('', array_reverse($number));
$number = $number . strval($stack);

return $number; 
     

}

创建一个php并在你的localhost Luhn(xxxxxxxx)中运行以确认。

答案 2 :(得分:2)

BAD

我真的无法相信那里有多少糟糕的实现。

  

IDAutomation有一个.NET assembly with a MOD10() function来创建,但它似乎不起作用。在Reflector中,代码对于它应该做的事情来说太长了。


BAD

This mess of a page实际上当前链接到维基百科(!)的Javascript有几个验证实现,当我调用每个验证实现时甚至不返回相同的值。


正确

page linked to from Wikipedia's Luhn page有一个似乎有效的Javascript编码器:

// Javascript
String.prototype.luhnGet = function()
{
    var luhnArr = [[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]], sum = 0;
    this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){
        sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]
    });
    return this + ((10 - sum%10)%10);
};

alert("54511187504546384725".luhnGet());​

正确

very useful EE4253页面验证校验位,并显示完整的计算和说明。


正确

我需要C#代码并最终使用此code project code

// C#
public static int GetMod10Digit(string data)
        {
            int sum = 0;
            bool odd = true;
            for (int i = data.Length - 1; i >= 0; i--)
            {
                if (odd == true)
                {
                    int tSum = Convert.ToInt32(data[i].ToString()) * 2;
                    if (tSum >= 10)
                    {
                        string tData = tSum.ToString();
                        tSum = Convert.ToInt32(tData[0].ToString()) + Convert.ToInt32(tData[1].ToString());
                    }
                    sum += tSum;
                }
                else
                    sum += Convert.ToInt32(data[i].ToString());
                odd = !odd;
            }

            int result = (((sum / 10) + 1) * 10) - sum;
            return result % 10;
        }

正确

这个validation code in C#似乎有用,如果有点笨拙的话。我只是用它来检查上面的内容是否正确。

答案 3 :(得分:0)

现在有一个基于原始问题/答案的github回购。见

https://github.com/xi-project/xi-algorithm

它也可以在packagist上找到

答案 4 :(得分:0)

这是一个可以帮助你的功能,它很简短,而且效果很好。

function isLuhnValid($number)
{
    if (empty($number))
        return false;

    $_j = 0;
    $_base = str_split($number);
    $_sum = array_pop($_base);
    while (($_actual = array_pop($_base)) !== null) {
        if ($_j % 2 == 0) {
            $_actual *= 2;
            if ($_actual > 9)
                $_actual -= 9;
        }
        $_j++;
        $_sum += $_actual;
    }
    return $_sum % 10 === 0;
}

答案 5 :(得分:0)

由于显示或链接到C#的其他答案均无效,因此我添加了经过测试的更具解释性的C#版本:

    /// <summary>
    /// Calculates Luhn Check Digit based on 
    /// https://en.wikipedia.org/wiki/Luhn_algorithm
    /// </summary>
    /// <param name="digits">The digits EXCLUDING the check digit on the end. 
    /// The check digit should be compared against the result of this method.      
    /// </param>
    /// <returns>The correct checkDigit</returns>
    public static int CalculateLuhnCheckDigit(int[] digits)
    {
        int sum = 0;
        bool isMultiplyByTwo = false;

        //Start the summing going right to left
        for (int index = digits.Length-1; index >= 0; --index) 
        {
            int digit = digits[index];

            //Every other digit should be multipled by two.
            if (isMultiplyByTwo) 
                digit *= 2;

            //When the digit becomes 2 digits (due to digit*2),
            //we add the two digits together.
            if (digit > 9) 
                digit = digit.ToString()
                  .Sum(character => (int)char.GetNumericValue(character));

            sum += digit;
            isMultiplyByTwo = !isMultiplyByTwo;
        }

        int remainder = sum % 10;

        //If theres no remainder, the checkDigit is 0.
        int checkDigit = 0; 

        //Otherwise, the checkDigit is the number that gets to the next 10
        if (remainder != 0)
            checkDigit = 10 - (sum % 10); 

        return checkDigit;
    }

其用法示例:

    public static bool IsValid(string userValue)
    {
        //Get the check digit from the end of the value
        int checkDigit = (int)char.GetNumericValue(userValue[userValue.Length - 1]);

        //Remove the checkDigit for the luhn calculation
        userValue = userValue.Substring(0, userValue.Length - 1); 
        int[] userValueDigits = userValue.Select(ch => (int)char.GetNumericValue(ch))
                                         .ToArray();

        int originalLuhnDigit = CalculateLuhnCheckDigit(userValueDigits);

        //If the user entered check digit matches the calcuated one,
        //the number is valid.
        return checkDigit == originalLuhnDigit;
    }