Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save pfx certificate to file with java code (ejbca)

i use EJBCA to generate a certificate from a CommonName. In java code i have generated private key and public key and then the csr for generate the certificate. Now i save the certificate in PEM format (.cer), but i need also private key so i want save with .pfx or p12 extension. How can i do? This is my actual code for generate certificate:

KeyPair keys;
    try {
        keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);   

        //SAVE PRIVKEY
        //PrivateKey privKey = keys.getPrivate();
        //byte[] privateKeyBytes = privKey.getEncoded();
        PKCS10CertificationRequest  pkcs10 = new PKCS10CertificationRequest("SHA256WithRSA",
                CertTools.stringToBcX509Name("CN=NOUSED"), keys.getPublic(), null, keys.getPrivate());
        //Print Privatekey
        //System.out.println(keys.getPrivate().toString());
        CertificateResponse certenv =  ws.certificateRequest(user1,
                                                               new String(Base64.encode(pkcs10.getEncoded())),
                                                                CertificateHelper.CERT_REQ_TYPE_PKCS10,
                                                                null,
                                                                CertificateHelper.RESPONSETYPE_CERTIFICATE);

        //Certificate certenv =  ejbcaraws.pkcs10Req("WSTESTUSER1","foo123",new 
        //String(Base64.encode(pkcs10.getEncoded())),null);

        return certenv.getCertificate (); 
    }catch (Exception e) {}

and with this i save the certificate:

File file = new File(path+"/"+ x509Cert.getSubjectDN().toString().replace("CN=", "") +".cer");

        FileOutputStream os = new FileOutputStream(file);  
        //os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));  
        //os.write(Base64.encode(x509Cert.getEncoded(), true));  
        //os.write("-----END CERTIFICATE-----".getBytes("US-ASCII"));  
        //os.close(); 

        PEMWriter pemWriter = new PEMWriter(new PrintWriter(os));
        pemWriter.writeObject(x509Cert);
        pemWriter.flush();
        pemWriter.close();
like image 893
luca Avatar asked Feb 18 '26 16:02

luca


1 Answers

I never use EJBCA, however if you have the certificate and the private key and you want to create a PKCS12 you can use setKeyEntry(String alias,byte[] key,Certificate[] chain) method from java.security.KeyStore to add the entry, and then store(OutputStream stream, char[] password) method to save the PKCS12 on a file (look at API for more details). Your code could be something like:

import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

public class SamplePKCS12 {

    public static void main(String args[]) throws Exception {

        String alias = // the alias for your key...
        PrivateKey key = // your private key
        Certificate[] chain = // an array with your EE certificate to your CA issuer
        // create keystore      
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        // add your key and cert        
        keystore.setKeyEntry(alias, key.getEncoded(), chain);
        // save the keystore to file
        keystore.store(new FileOutputStream("/tmp/keystore.p12"), "yourPin".toCharArray());
    }
}

Note I suppose that you have your certificate and your private key as you said in your question. To work with PKCS12 you need SunJSSE provider (which is normally loaded by default), or alternatively you can use BouncyCastle provider.

Hope this helps,

like image 159
albciff Avatar answered Feb 20 '26 04:02

albciff