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?
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?
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.");
}
}
As others have noted, if you have a RSA CRT KEY
, then you can extract the public key from that. However it is actually not possible to retrieve a public key from a pure private key.
The reason for that is easy: When generating RSA keys, there is actually no difference between the private and the public key. One is choosen to be private, the remaining one is public then.
So if you could compute the public key from a pure private key, you could by Definition compute the private key from the public key...
If you have both, you can actually easily test if they match:
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 );
This is absolutely wrong! you can always get a public key from private key but you can never get a private key from public key. This is why RSA is asymmetric algorithm!
If you have an object of type RSAPrivateKey
then you need to do two things:
privateKey.getModulus()
65537
.After getting modulus and public exponent, you can follow PeteyB's answer.
AFAIK you cannot derive the other key of an RSA key pair, given one key. That would be equivalent to breaking RSA.
For testing a pair, just encrypt something using one key and decrypt it using the other to see if you get the original result back.