使用大数字作为数组

时间:2011-08-29 17:02:06

标签: php

我必须为RSA使用大数字,所以我使用数组:

$number1 = array(1234567, 7898765);
$number2 = array(9876543, 2123456);  

如何将它们与快速算法相乘并计算modular multiplicative inverse

2 个答案:

答案 0 :(得分:2)

<强>算法

要说b是a的模块化逆模m,就是说

a * b = 1(mod m)

对于任何整数a,当且仅当a和b是相对素数时,存在这样的逆b。使用扩展的欧几里得算法,我们可以找到一个x和y,使得a * x + m * y = 1.从那里可以看出a * x = 1(mod m),因此x是a的模数逆。 / p>

<强>代码

我知道你想在PHP中使用它,但我有C ++版本,也许你以后可以把它转换成PHP。

int x = px;
int y = py;

//Setup initial variables
//Maintain throughout that ax * px + bx * py = x and that ay * px + by * py = y
int ax = 1;
int ay = 0;
int bx = 0;
int by = 1;

//Perform extended gcd
while(x)
{
    if(x <= y)
    {
        int m = y / x;
        y -= m * x;
        ay -= ax * m;
        by -= bx * m;
    }
    else
    {
        swap(x, y);
        swap(ax, ay);
        swap(bx, by);
    }
}

//you can assert that ay * px + by * py = y = gcd(px, py)
//you can assert that ax * px + bx * py = x = 0

//If we're taking the modular inverse of px (mod py), then for it to exist gcd(px, py) = 1
//If it does exist, it is given by ay (mod py)
int inverse = ay % py;
if(inverse < 0) inverse += py;

答案 1 :(得分:2)

您可能想要使用gmpbcmath。这些是用于处理大量数据和计算的php库。