如何通过提供PrivateKey来获取RSA PublicKey?
我正在寻找一个Java函数,它将获得一个RSA PrivateKey并将返回正确的RSA PublicKey?
或者,是否有一个函数可以告诉我们RSA PrivateKey / PublicKey是否有效?
如果您将私钥作为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(); }
我想不出你需要这个的任何好理由。 但这里是:
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."); } }
正如其他人所说,如果您有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 );
这绝对是错的! 您始终可以从私钥获取公钥,但您永远无法从公钥获取私钥。 这就是RSA不对称算法的原因!
如果你有一个RSAPrivateKey
类型的对象,那么你需要做两件事:
- 获得模数。 简单:
privateKey.getModulus()
- 计算公共指数。 这有点棘手,但并非不可能。 请参阅public exponent的定义 。 通常,公共指数是
65537
。
获得模数和公共指数后,您可以按照PeteyB的答案。
AFAIK如果给出一个密钥,则无法导出RSA密钥对的其他密钥。 这相当于打破RSA。
对于测试一对,只需使用一个密钥加密某个东西,然后使用另一个密钥对其进行解密,看看是否得到了原始结果。