实现RSA算法的小故障

发布于 2024-09-30 12:43:52 字数 726 浏览 1 评论 0原文

我正在尝试实现 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为守护你 2024-10-07 12:43:52

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

BigInteger d = e.modInverse(totient);

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

The comments are correct. You should use the modInverse() method of BigInteger to compute an inverse. So the last line should be:

BigInteger d = e.modInverse(totient);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文