I am looking for a Java function that will get an RSA PrivateKey and will return the correct RSA PublicKey?
Alternatively, is there a function that will tell us if the RSA PrivateKey/PublicKey is valid?
RSA key is a private key based on RSA algorithm. Private Key is used for authentication and a symmetric key exchange during establishment of an SSL/TLS session. It is a part of the public key infrastructure that is generally used in case of SSL certificates.
There is a misconception on what the private key is. The private key is just the (d,n) pair and, given only that, it is infeasible to generate the public key from it unless you can assume that the public exponent is 65537, which is the case on almost all rsa keys.
If you have your private key as an RSAPrivateCrtKey object, you can get the public exponent as well as modulous.
Then you could create the public key like so:
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();
}
I can't think of any good reason you'd need this. But here it is:
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.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With