c360ian
c360ian

Reputation: 1303

How to convert x509 Cert and Key to a pkcs12 file

To convert a pem file containing a x509 certificate + private key into a pkcs12 (.p12) file, the following command is being used:

openssl pkcs12 -export -inkey cert_pkey.pem -in cert_pkey.pem -out cert.p12

I am trying to accomplish the same programatically using Java with BouncyCastle library. I am able to extract the X509Cert from the PEMObject but the Private key has been confusing.

Any help in piecing together the steps is appreciated:

  1. Open cert_pkey.pem file stream using PEMParser
  2. Get the X509 Certificate from PemObject (done)
  3. Get the private key from the PemObject (how?)
  4. Create KeyStore of instance type PKCS12 with password

Upvotes: 2

Views: 10207

Answers (2)

c360ian
c360ian

Reputation: 1303

Finally got around how to get the cert and key separately - not sure why it worked out the way it worked out:

PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(certStream)));
Object pemCertObj = pemParser.readObject();
PemObject pemKeyObj = pemParser.readPemObject();

PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemKeyObj.getContent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(privKeySpec);

Security.addProvider(new BouncyCastleProvider());
X509CertificateHolder certHolder = (X509CertificateHolder)pemCertObj;
X509Certificate x509cert = (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certHolder);

I got the hint when I looked up the .getType() on permCertObj and permKeyObj and got RSA CERT and RSA PRIVATE KEY respectively returned.

Couldn't figure out the difference between readObject() and readPemObject()

Upvotes: 3

Avi Kama
Avi Kama

Reputation: 1

The PEMParser class will parse just about anything from PEM format. You can read the object from the file using that parser - if you'll print the class of that object you'l;l see it's a PEMKeyPair. That can be converted to a regular KeyPair using JcaPEMKeyConverter.

public KeyPair importKeyFromPemFile(String filePath)
{
    try (FileReader reader = new FileReader(filePath))
    {
        PEMParser pemParser = new PEMParser(reader);
        PEMKeyPair pemKeyPair = (PEMKeyPair)pemParser.readObject()
        return new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
    }
    catch (IOException | PEMException e)
    {
        throw new RuntimeException(e)
    }
}

Upvotes: 0

Related Questions