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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24911238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:33:35  来源:igfitidea点击:

programmatically import .cer certificate into keystore

javakeystorepkcs#12key-management

提问by Pali

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.javaand 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.

如何将 .p12 证书从类路径导入 java 密钥库?首先,我使用了 InstallCert https://code.google.com/p/java-use-examples/source/browse/trunk/src/com/aw/ad/util/InstallCert.java并做了一些更改,因此服务器证书将被导入到 java 安装目录中的密钥库中。这工作正常,但现在我想从我的类路径加载证书。

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

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

采纳答案by Pali

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 dont use the ClassLoader, use the Class itselfe:

对于 Java Web Start,不要使用 ClassLoader,使用 Class 本身:

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

回答by Feng Zhang

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

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