我正在寻找一个Java函数,该函数将获取RSA PrivateKey并返回正确的RSA PublicKey。
或者,是否有一种函数可以告诉我们RSA PrivateKey / PublicKey是否有效?
或者,是否有一种函数可以告诉我们RSA PrivateKey / PublicKey是否有效?
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.");
}
}
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 );
如果您有一个类型为RSAPrivateKey
的对象,则需要执行两个操作:
privateKey.getModulus()
65537
。在获取模数和公共指数之后,您可以按照PeteyB的答案进行操作。
public PublicKey generatePublicKey(String privateKey) {
try {
KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
byte[] encodedPv = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpecPv = new PKCS8EncodedKeySpec(encodedPv);
RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) kf.generatePrivate(keySpecPv);
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent());
return kf.generatePublic(publicKeySpec);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
PKCS8EncodedKeySpec keySpecPv = new PKCS8EncodedKeySpec(encodedPv);
RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) kf.generatePrivate(keySpecPv);
RSAPrivateCrtKey
类的方法rsaPrivateKey.getPublicExponent()
可以获得公钥指数。RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent());
return kf.generatePublic(publicKeySpec);