Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
spy Avatar asked Aug 31 '25 18:08

spy


1 Answers

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....
like image 53
spy Avatar answered Sep 02 '25 06:09

spy