2010-10-30 110 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循環的條件。也許最後的&&應該是||?就個人而言,我會使用一個單獨的方法,返回正確範圍內的隨機數。