【发布时间】:2017-09-22 17:59:15
【问题描述】:
我正在尝试使用扩展欧几里得算法计算 RSA 的 d。然而,每次我跑进去,结果都是负面的。
这是算法的代码,假设 a 是 phi,e 是 65537:
BigInteger exEuc(BigInteger a, BigInteger b){
BigInteger x = 0;
BigInteger prevX = 1; //holds the previous value of x
BigInteger y = 1;
BigInteger prevY = 0; //holds the previous value of y
BigInteger temp, q;
while(b != 0){
q = a / b;
temp = b;
b = a % b;
a = temp;
temp = x;
x = prevX-q*x;
prevX = temp;
temp = y;
y = prevY-q*y;
prevY = temp;
}
return prevY; //this ends up being d
}
我已经使用 e*d mod phi 测试了结果,它给出了预期的 1,但我知道 d 不应该是负数。知道这里出了什么问题吗?
【问题讨论】:
-
您是否尝试过使用 unsigned 大数字?还是将其打印为 无符号 数字?
-
您是否尝试过使用调试器单步执行您的代码,以找出结果为负数的位置以及原因?
-
是的,这就是欧几里得算法的工作方式。对于计算逆运算,您总是需要正余数,you need to add
bto the answer if it is negative。 -
当我添加一个 OR b 时,数字仍然是负数,并且在这两种情况下,我尝试时 e*dmodphi=1 测试都失败
-
我不是你说的那样,但如果你将
phi添加到 d 中,它将是正数,并且 e*d 将等于 1 mod phi。
标签: c++ encryption rsa