Search code examples
javarsax509certificatex509jks

Convert RSAPublic key to X509Certificate (Java)


Q: Is it possible to read a RSA key pair from a Java Key Store can capture the public key subject identity from the public key?

I've generated a RSA with SHA1 2048 bit key using the Java Keytool and stored the key pair in a JKS file. I can load the key using the code from here: https://stackoverflow.com/a/26711907/1203182 however I'm getting an RSAPublicKey, not an X509Certificate. The RSA Public Key doesn't have any methods to find the Subject Identity or DN from the public key.

Is there a way to convert the RSA Public Key or somehow derive the X509 certificate from it? Or maybe I'm just not understanding something.


Solution

  • And as usual, I came up with my own answer seconds after posting this. Talk about rubber duck coding. The solution was rather simple, I was looking in the wrong place. Code snippet below...

    Key key = keystore.getKey(alias, "password".toCharArray());
    if (key instanceof PrivateKey) {
      // Get certificate of public key
      Certificate cert = keystore.getCertificate(alias);
    
      //Answer > get the DN from 'cert.getSubjectDN()`
    
      // Get public key
      PublicKey publicKey = cert.getPublicKey();
      //publicKey is NOT where you can get the certificate DN....