Apache HttpClient和PEM证书文件

时间:2010-11-10 16:26:57

标签: java pem apache-httpclient-4.x

我想以编程方式访问需要客户端证书的站点,我在PEM文件中有这些证书。在这个应用程序中,我不想将它们添加到我的密钥库,使用keytool或openssl,如果我可以避免这样做。我需要直接在代码中处理它们。

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("https://my.secure.site.com/url");

    // TODO: Specify ca.pem and client.pem here?

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        entity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();

如何通过请求“发送”证书?

2 个答案:

答案 0 :(得分:6)

最简单的可能是使用.p12格式(虽然其他工作也很好 - 只需要注意base64块之外的额外行)并添加如下内容:

// 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");

或者 - 使用

之类的东西
    KeyStore ks = KeyStore.getInstance( "pkcs12" );
    ks.load( new FileInputStream( ....), "mypassword".toCharArray() );

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

反而在上面创建。而不是依赖于系统属性 - 使用类似的东西:

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

将它与密钥库分开。

DW。

答案 1 :(得分:-1)

您可以从KeyStore文件中创建.pem,如下所示:

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;
}