2010-10-30 53 views
1

我想实现RSA algorithm,但由于某种原因,我的代码下面并没有产生正确的结果(注意只显示了相关的代码)。实施RSA算法的小故障

BigInteger n = p.multiply(q); 
BigInteger totient = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); 

Random rand = new Random(); 
BigInteger e; 
do 
{ 
e = new BigInteger(totient.bitLength(), rand); 
} while ((e.compareTo(BigInteger.ONE) <= 0 || e.compareTo(totient) >= 0) 
    && !((e.gcd(totient)).equals(BigInteger.ONE))); 

BigInteger d = (BigInteger.ONE.divide(e)).mod(totient); 
使用127和131作为主号码输入

样本输出(注意,16637是正确的,但7683和0都没有):

Public Key: (16637,7683) 
Private Key: (16637,0) 

感谢您的帮助!

+0

向我们展示一些输出 – Woot4Moo 2010-10-30 01:26:12

+0

添加了示例输出。 – 2010-10-30 01:28:18

+0

我不确定,但BigInteger d =(BigInteger.ONE.divide(e)).mod(totient);有99%的可能性。 () – Jonathan 2010-10-30 01:41:16

回答

0

评论是正确的。您应该使用BigInteger的modInverse()方法来计算逆。所以最后一行应该是:

BigInteger d = e.modInverse(totient); 

而且,我不能完全肯定我理解在while循环的条件。也许最后的&&应该是||?就个人而言,我会使用一个单独的方法,返回正确范围内的随机数。