programmatically import .cer certificate into keystore

How can I import a .p12 certificate from the classpath into the java keystore? First I used the InstallCert and did some changes so the server certificate will be imported into the keystore in the java install directory. This works fine but now I want to load a certificate from my classpath.

EDIT: I just use a .cer certificate, see next answer


The answer:

    InputStream certIn = ClassLoader.class.getResourceAsStream("/package/myCert.cer");

    final char sep = File.separatorChar;
    File dir = new File(System.getProperty("java.home") + sep + "lib" + sep + "security");
    File file = new File(dir, "cacerts");
    InputStream localCertIn = new FileInputStream(file);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(localCertIn, passphrase);
    if (keystore.containsAlias("myAlias")) {

    BufferedInputStream bis = new BufferedInputStream(certIn);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        keystore.setCertificateEntry("myAlias", cert);


    OutputStream out = new FileOutputStream(file);, passphrase);

For Java Web Start dont use the ClassLoader, use the Class itselfe:

InputStream certIn = Certificates.class.getResourceAsStream("/package/myCert.cer");

Need Your Help

Convert a string into an int

ios objective-c xcode ios4

I'm having trouble converting a string into an integer. I googled it but all I can find is how to convert an int into a string. Does anyone know how to do it the other way around? Thanks.

What is the difference between Eclipse 3.7 and Eclipse 4.1?

java eclipse java-ee eclipse-indigo

I see there are two main distributions of Eclipse going on - One is on 3.6, 3.7, 3.8 path and the other is 4.0, 4.1 path(