如何通过提供PrivateKey来获取RSA PublicKey?

时间:2012-07-05 13:28:38

标签: java security cryptography rsa

我正在寻找一个能够获得RSA PrivateKey的Java函数并返回正确的RSA PublicKey吗?

或者,是否有一个函数可以告诉我们RSA PrivateKey / PublicKey是否有效?

6 个答案:

答案 0 :(得分:10)

如果您将私钥作为RSAPrivateCrtKey对象,则可以获得公共指数以及模数。

然后您可以像这样创建公钥:

RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(modulus, exponent);   
try {   
     KeyFactory keyFactory = KeyFactory.getInstance("RSA");   

     PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);   
} catch (Exception e) {   
     e.printStackTrace();   
} 

答案 1 :(得分:4)

我想不出你需要这个的任何好理由。但这是:

static boolean isValidRSAPair(KeyPair pair)
{
  Key key = pair.getPrivate();
  if (key instanceof RSAPrivateCrtKey) {
    RSAPrivateCrtKey pvt = (RSAPrivateCrtKey) key;
    BigInteger e = pvt.getPublicExponent();
    RSAPublicKey pub = (RSAPublicKey) pair.getPublic();
    return e.equals(pub.getPublicExponent()) && 
      pvt.getModulus().equals(pub.getModulus());
  }
  else {
    throw new IllegalArgumentException("Not a CRT RSA key.");
  }
}

答案 2 :(得分:1)

正如其他人所说,如果您有RSA CRT KEY,那么您可以从中提取公钥。但是,实际上可以从纯私钥中检索公钥。

原因很简单:生成RSA密钥时,私钥和公钥之间实际上没有区别。一个选择是私人的,剩下的一个是公开的。

因此,如果您可以从纯私钥计算公钥,则可以通过Definition从公钥计算私钥...

如果你有两者,你可以很容易地测试它们是否匹配:

RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
return rsaPublicKey.getModulus().equals( rsaPrivateKey.getModulus() )
  && BigInteger.valueOf( 2 ).modPow(
  rsaPublicKey.getPublicExponent().multiply( rsaPrivateKey.getPrivateExponent() )
    .subtract( BigInteger.ONE ), 
  rsaPublicKey.getModulus() ).equals( BigInteger.ONE );

答案 3 :(得分:0)

如果你有RSAPrivateKey类型的对象,那么你需要做两件事:

  1. 获得模数。简单:privateKey.getModulus()
  2. 计算公共指数。这有点棘手,但并非不可能。请参阅definition of public exponent。通常,公共指数为65537
  3. 获得模数和公共指数后,您可以按照PeteyB的回答。

答案 4 :(得分:-1)

这绝对是错的!您始终可以从私钥获取公钥,但您永远无法从公钥获取私钥。这就是RSA不对称算法的原因!

答案 5 :(得分:-3)

AFAIK如果给出一个密钥,则无法导出RSA密钥对的其他密钥。这相当于打破RSA。

对于测试一对,只需使用一个密钥对某个密钥进行加密,然后使用另一个密钥对其进行解密,以查看是否返回原始结果。

相关问题