programmatically import .cer certificate into keystore

浪尽此生 提交于 2019-11-30 03:46:25
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:

InputStream certIn = Certificates.class.getResourceAsStream("/package/myCert.cer");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!