Apache HttpClient and PEM certificate files

与世无争的帅哥 提交于 2019-12-03 04:05:25
Dirk-Willem van Gulik

Easiest may well be to use the .p12 format (though the others work fine too - just be careful with extra lines outside the base64 blocks) and add something like:

// systems I trust
System.setProperty("javax.net.ssl.trustStore", "foo");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

// my credentials
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
System.setProperty("javax.net.ssl.keyStore", "cert.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

Or alternatively - use things like

    KeyStore ks = KeyStore.getInstance( "pkcs12" );
    ks.load( new FileInputStream( ....), "mypassword".toCharArray() );

    KeyStore jks = KeyStore.getInstance( "JKS" );
    ks.load(...

to create above on the fly instead. And rather than rely on the system property - use somethng like:

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(aboveKeyStore, "changeme".toCharArray());
    sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(kmf.getKeyManagers(), null, null);

which keeps it separate from keystore.

DW.

You can create a KeyStore from .pem files like so:

private KeyStore getTrustStore(final InputStream pathToPemFile) throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);

    // load all certs
    for (Certificate cert : CertificateFactory.getInstance("X509")
            .generateCertificates(pathToPemFile)) {
        final X509Certificate crt = (X509Certificate) cert;

        try {
            final String alias = crt.getSubjectX500Principal().getName();
            ks.setCertificateEntry(alias, crt);
            LOG.info("Added alias " + alias + " to TrustStore");
        } catch (KeyStoreException exp) {
            LOG.error(exp.getMessage());
        }
    }

    return ks;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!