I'm using Java and BouncyCastle to generate a CA certificate, the CA issues several user Certificates, these Certificates are stored on a Data Base with their private key. How can I generate a certificate file that can be installed by Windows in which the operating system recognizes the private key and the certificate details ? If I save the certificate details from X509Certificate class to PEM file the certificate details are recognized but without the private key.
Any help ?
Thanks.
Normally you generate a private key and a certificate signing request, you send the csr to the CA, and the CA issues the certificate. Finally you can generate a keystore
and store the private key and the certificate together on it. So I don't understand how is your CA storing the private key in a data base since the private key is not send to the CA.
Omitting this information (maybe you've a selfsigned CA for infrastructure purposes, data base it's not safe to store privateKeys, etc), the thing is; to load a private key and a certificate on windows you need a keystore
file (typically for windows a pfx
or pkcs12
) instead of only a certificate. To do so using java and bouncycastle as you ask you can use the follow sample code (as you said I suppose that you have the certificate and the private key):
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Sample {
public static void main(String[] args) throws Exception {
// generate your certificate
CertificateFactory cf = CertificateFactory.getInstance("X509", new BouncyCastleProvider());
Certificate yourCert = cf.generateCertificate(new FileInputStream("C:/your_certificate_path"));
// here you can add also the issuer of your cert
Certificate[] certChain = { yourCert };
// depending on your private key format you've a different
// ways to parse its
Key privatekey = null;//...
String alias = "yourKSEntry";
// generate the keystore
KeyStore ks = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
// necessary to init a new keystore
ks.load(null, null);
String keyPass = null;// your key pass or null if the key file has no password
// adds the key and cert to the keystore
ks.setKeyEntry(alias, privatekey, null, certChain);
// save to file in order that then you
// can install on windows keystore
ks.store(new FileOutputStream("C:/where_save_your_keystore.p12"), "your_keystore_pass".toCharArray());
}
}
Hope this helps,