以编程方式将.cer证书导入密钥库

问题描述 投票:12回答:2

如何将.p12证书从类路径导入到Java密钥库中?首先,我使用InstallCert https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java进行了一些更改,以便将服务器证书导入到Java安装目录中的密钥库中。效果很好,但现在我想从类路径中加载证书。

编辑:我只使用.cer证书,请参阅下一个答案

java keystore pkcs#12 key-management
2个回答
25
投票

答案:

    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本身:

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

0
投票

我也遇到“ java.io.FileNotFoundException:C:\ Program Files(x86)\ Java \ jre1.8.0_45 \ lib \ security \ cacerts(访问被拒绝)”问题。我必须转到文件夹\ securiyy并手动授予权限才能访问h


推荐问答