代码之家  ›  专栏  ›  技术社区  ›  Donald T

RSA算法实现中的小故障

  •  1
  • Donald T  · 技术社区  · 14 年前

    我正在努力实现 RSA algorithm ,但由于某些原因,下面的代码无法产生正确的结果(请注意,仅显示相关代码)。

    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)
    

    谢谢你的帮助!

    1 回复  |  直到 14 年前
        1
  •  0
  •   President James K. Polk    14 年前

    评论是正确的。你应该使用 modInverse()

    BigInteger d = e.modInverse(totient);
    

    另外,我不完全确定我是否理解while循环中的条件。也许是最后一次 && 应该是一个 ||