12

How can I import a .p12 certificate from the classpath into the java keystore? First I used the InstallCert https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java 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

Pali
  • 1,259
  • 1
  • 12
  • 36

2 Answers2

27

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")) {
    certIn.close();
    localCertIn.close();
    return;
}
localCertIn.close();

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

certIn.close();

OutputStream out = new FileOutputStream(file);
keystore.store(out, passphrase);
out.close();

For Java Web Start don't use the ClassLoader, use the Class itself:

InputStream certIn = Certificates.class.getResourceAsStream("/package/myCert.cer");
Josh Correia
  • 2,133
  • 1
  • 17
  • 29
Pali
  • 1,259
  • 1
  • 12
  • 36
  • 2
    any clue how to solve the problem about access denied? (though i am administrator) java.io.FileNotFoundException: C:\Program Files (x86)\Java\jre1.8.0_45\lib\security\cacerts (Access is denied) – lumo Jun 07 '15 at 19:12
  • 1
    Maybe the file is already in use by another process? Maybe you have some permission issues of the files and folders and Java itself dont have permission? Otherwise no clue ... also this solution worked in Java7 so there maybe this no longer works in Java8? – Pali Jun 08 '15 at 06:54
-1

I run into "java.io.FileNotFoundException: C:\Program Files (x86)\Java\jre1.8.0_45\lib\security\cacerts (Access is denied)" issue as well. I have to go to the folder \securiyy and grant permission manually to access h

Feng Zhang
  • 920
  • 8
  • 16