以编程方式将.cer证书导入密钥库 [英] programmatically import .cer certificate into keystore

查看:155
本文介绍了以编程方式将.cer证书导入密钥库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

编辑:我只是使用.cer证书,看下一个答案

I just use a .cer certificate, see next 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();

对于Java Web Start,请不要使用ClassLoader,请使用Class itselfe:

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

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

这篇关于以编程方式将.cer证书导入密钥库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆