BigInteger正在发生一些奇怪的事情。我正在尝试为分配实现自己的RSA。 代码如下,并且使用小数字可以很好地工作。 如果我选择p = 11,q = 5,e = 7且d = 23,则终端上的输出为
Original message is: 19
Encryption of message is: 24
Decryption of message is: 19
如果我用更大的数字改变数字,它就不再起作用了。以下代码:
import java.math.BigInteger;
class RSAdumb{
public static void main(String[] args) {
BigInteger m = new BigInteger("19");
BigInteger p = new BigInteger("99989");
BigInteger q = new BigInteger("99991");
BigInteger n = p.multiply(q);
BigInteger e = new BigInteger("65537");
BigInteger d = new BigInteger("4232182107");
BigInteger c = m.modPow(e,n); //Returns a BigInteger whose value is (this^e mod n)
BigInteger check = c.modPow(d,n);
System.out.println("Original message is: "+m.toString());
System.out.println("Encryption of message is: "+c.toString());
System.out.println("Decryption of message is: "+check.toString());
}
}
输出:
Original message is: 19
Encryption of message is: 5609974360
Decryption of message is: 2710593036
我已经两次检查过这些数字对于RSA是好的。精确地
e*d = 4232182107 * 65537 = 1 mod 9998000099
,其中
9998000099 = 99989 * 99991 (both primes)
现在,根据我的理解,BigInteger应该是无限的,所以它不应该是边界问题......而不是可能的?对于我的任务,我总是可以用小数字来实现它,但这非常荒谬......
答案 0 :(得分:5)
e
和d
的要求并不是他们的产品与1(mod n )一致,而是他们的产品必须与1一致(mod φ( n )),根据Wikipedia page on RSA。
这是totient函数,对于2个素数乘以(p - 1)(q - 1)
或997800120。
ed (modφ( n ))的结果不是1
,而是32589339
。
你的小数字起作用的原因是因为5和11的φ( n )是4 * 10 = 40,而7 * 23(mod 40)是1
。< / p>
您需要为较大的数字选择合适的d
常量。这是e
相对于φ(n)
的模数倒数,可以使用BigInteger
's modInverse
method计算。
BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger d = e.modInverse(phi);
这表明d
为2598113033
。使用d
会产生正确的输出。
Original message is: 19
Encryption of message is: 5609974360
Decryption of message is: 19
答案 1 :(得分:3)
您在计算私人指数 d 时出错了。
首先,您需要计算 n 的 phi :φ(n) = φ(p)φ(q) = (p − 1)(q − 1) = n - (p + q -1)
BigInteger phi = n.subtract(p.add(q).subtract(BigInteger.ONE));
然后你需要将 e 的模块化反转与 phi 作为模数来获得 d :
d = e.modInverse(phi);
会产生d = 2598113033
。
供参考:Wikipedia