3

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.

Community
  • 1
  • 1
spy
  • 3,199
  • 1
  • 18
  • 26

2 Answers2

1

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....
spy
  • 3,199
  • 1
  • 18
  • 26
0

I would recommend using Bouncy Castle when dealing with encryption and decryption in Java.

Here is something that could give you some information (I think he wants to do the same as you want):

Read public key from file in keystore

The code example there looks like this:

PEMParser pemParser = new PEMParser(new StringReader(certPEMData));
    Object parsedObj = pemParser.readObject();
    System.out.println("PemParser returned: " + parsedObj);
    if (parsedObj instanceof X509CertificateHolder)
    {
        X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) parsedObj;
        return x509CertificateHolder.getSubjectPublicKeyInfo().getPublicKeyData().getString();
    }
    else
    {
        throw new RuntimeException("The parsed object was not an X509CertificateHolder.");
    }

And here you have the website of the Bouncy Castle library which should have some information for you too:

Bouncy Castle

And if you are lazy here is the link to their newest version. Include that JAR-File in your build-path and you can just copy-paste the code above.

Bouncy Castle library direct download

Community
  • 1
  • 1
SteapStepper69
  • 1,247
  • 10
  • 22