11

我正在寻找一个可以获取 RSA PrivateKey 并返回正确的 RSA PublicKey 的 Java 函数?

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

4

5 回答 5

13

如果您将私钥作为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();   
} 
于 2012-07-05T16:16:21.323 回答
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.");
  }
}
于 2012-07-05T16:34:18.003 回答
1

正如其他人所指出的,如果您有RSA CRT KEY,那么您可以从中提取公钥。然而,实际上不可能从纯私钥中检索公钥。

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

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

如果两者都有,您实际上可以轻松测试它们是否匹配:

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 );
于 2015-02-25T15:46:17.197 回答
0

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

  1. 获取模数。简单的:privateKey.getModulus()
  2. 计算公共指数。这有点棘手,但并非不可能。请参阅公共指数的定义。通常,公共指数是65537

获得模数和公共指数后,您可以按照 PeteyB 的回答。

于 2013-07-07T13:03:05.673 回答
-4

AFAIK 给定一个密钥,您无法派生 RSA 密钥对的另一个密钥。这相当于破坏了 RSA。

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

于 2012-07-05T13:33:04.587 回答