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

Das*_*Das 11 java security cryptography rsa

我正在寻找一个Java函数,它将获得一个RSA PrivateKey并将返回正确的RSA PublicKey?

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

Pet*_*y B 11

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

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

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();   
} 
Run Code Online (Sandbox Code Playgroud)


eri*_*son 5

我想不出有什么好的理由你需要这个。但这里是:

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.");
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 -4

据我所知,给定一个密钥,您无法导出 RSA 密钥对中的另一个密钥。这相当于破解 RSA。

要测试一对,只需使用一个密钥加密某些内容并使用另一个密钥解密,看看是否能得到原始结果。

  • @MK那是因为公钥包含在私钥中。 (5认同)
  • 我认为这是错误的。根据http://stackoverflow.com/questions/5244129/openssl-use-rsa-private-key-to-generate-public-key,您可以从私钥获取RSA公钥。 (3认同)