Peter Quiring
Peter Quiring

Reputation: 1706

How to convert JKS certs/keys to BouncyCastle certs/keys

In my java app I have a JKS keystore with a self-signed cert/key. I need to load them and convert them to BouncyCastle types.

I am using java.security.KeyStore to load the cert/key which gives me java.security.cert.Certificate and java.security.Key.

How do I then convert these to a format that BouncyCastle uses (org.bouncycastle.asn1.x509.Certificate etc.)

If I use Security.addProvider(new BouncyCastleProvider()); will that make the KeyStore return different types???

Or does BC have it's own KeyStore API (note: the keystore is in JKS/SUN format).

Thanks

Upvotes: 1

Views: 2408

Answers (1)

Peter Quiring
Peter Quiring

Reputation: 1706

I figured it out, here is some pseudo code.

To convert certs:

byte data[] = java.security.cert.Certificate.getEncoded();
org.bouncycastle.asn1.x509.Certificate.getInstance(data);

To convert keys:

      byte data[] = java.securty.Key.getEncoded();
      if (isRSA) {
        RSAPrivateKey rsa = RSAPrivateKey.getInstance(data);
        return new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(),
          rsa.getPrivateExponent(), rsa.getPrime1(), rsa.getPrime2(), rsa.getExponent1(),
          rsa.getExponent2(), rsa.getCoefficient());
      } else {
        return PrivateKeyFactory.createKey(data);
      }

Upvotes: 2

Related Questions