Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a RSA PublicKey by giving a PrivateKey?

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?

like image 738
DasDas Avatar asked Jul 05 '12 13:07

DasDas


People also ask

What is RSA Privatekey?

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.

Can you derive RSA public key from private key?

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.


2 Answers

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();   
} 
like image 127
Petey B Avatar answered Oct 03 '22 21:10

Petey B


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.");
  }
}
like image 20
erickson Avatar answered Oct 03 '22 20:10

erickson