Search code examples
javabouncycastlex509

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

Solution

  • 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()