实现RSA算法的小故障
我正在尝试实现 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)
感谢您的帮助!
I am trying to implement the RSA algorithm, but for some reason my code below doesn't produce correct results (note that only the relevant code is shown).
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);
Sample output using 127 and 131 as the prime-number inputs (note that 16637 is correct, but 7683 and 0 aren't):
Public Key: (16637,7683)
Private Key: (16637,0)
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
评论是正确的。您应该使用 modInverse() 方法来计算逆数。所以最后一行应该是:
另外,我不完全确定我理解 while 循环中的条件。也许最后一个
&&
应该是||
?就我个人而言,我会使用一个单独的方法来返回正确范围内的随机数。The comments are correct. You should use the modInverse() method of BigInteger to compute an inverse. So the last line should be:
Also, I'm not completely certain I understand the condition in the while loop. Maybe the last
&&
should be an||
? Personally, I would use a separate method that returns a random number in the correct range.