如何将类路径中的.p12证书导入java密钥库?首先,我使用了InstallCert https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java并进行了一些更改,因此服务器证书将被导入到java安装目录中的密钥库中。这工作正常但现在我想从我的类路径加载证书。
编辑:我只使用.cer证书,请参阅下一个答案
答案 0 :(得分:24)
答案:
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();
对于Java Web Start,请不要使用ClassLoader,请使用Class itselfe:
InputStream certIn = Certificates.class.getResourceAsStream("/package/myCert.cer");
答案 1 :(得分:0)
我也遇到“ java.io.FileNotFoundException:C:\ Program Files(x86)\ Java \ jre1.8.0_45 \ lib \ security \ cacerts(访问被拒绝)”问题。我必须转到文件夹\ securiyy并手动授予权限才能访问h