最近在工作中遇到这样一个问题:需要将 Postman 中双向认证的接口移植到现有的自动化测试平台中,测试平台底层是使用 Java+HttpClient 实现。Postman 中的证书配置如下:

可以看到 CRT file 和 KEY file 都是.pem 结尾的,这两个文件我们需要拿到,后续使用 HttpClient 实现也需要用到这两个文件。那 HttpClient 要怎么实现双向认证呢?接下来我们一步步实现。

第一步:我们利用两个 pem 结尾的文件生成.p12 结尾的证书文件。
使用的命令为:

openssl pkcs12 -export -in XXX.pem -inkey XXXXX-key.pem -out XXXX.p12

注意:生成过程中会要你输入密码,如果有则输入,无则直接按回车两下。
这样我们就拿到了 p12 结尾的证书文件。

第二步:Java 生成证书
1、编译:javac InstallCert.java
2、运行:java InstallCert 要访问的网址
3、会在相应的目录下产生一个名为 ‘jssecacerts’ 的证书。将证书 copy 到 $JAVA_HOME/jre/lib/security 目录下
代码如下:

import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }

        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP
                    + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] {tm}, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println
                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }

        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);

        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();

        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println
                ("Added certificate to keystore 'jssecacerts' using alias '"
                        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

}

第三步:利用 httpclient 带证书请求,以下是创建 client 的步骤 (可能部分代码你不需要,看懂意思即可)

public static CloseableHttpClient buildHTTPClient(URL url,) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
        CloseableHttpClient httpClient = null;
        if (httpClient == null) {
            SystemDefaultDnsResolver systemDefaultDnsResolver = SystemDefaultDnsResolver.INSTANCE;
            SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] xcs, String string) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = null;
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                keyStore.load(new FileInputStream("这里是我们存放p12证书的路径", "这里是证书的密码,如果没有密码则为空字符串".toCharArray());
                SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).loadKeyMaterial(keyStore, "这里是证书的密码,如果没有密码则为空字符串.toCharArray()).build();
                sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, (String[])null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            } else {
                sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            }

            Registry<Object> registry = RegistryBuilder.create().register("https", sslsf).register("http", CONNECTION_SOCKET_FACTORY).build();
            PoolingHttpClientConnectionManager pHCCM = new PoolingHttpClientConnectionManager(new DefaultHttpClientConnectionOperator(registry, (SchemePortResolver)null, systemDefaultDnsResolver), (HttpConnectionFactory)null, 2000L, TimeUnit.MILLISECONDS);
            pHCCM.setValidateAfterInactivity(1700);
            IgnoreSpecProvider ignoreSpecProvider = new IgnoreSpecProvider();
            Registry registry1 = RegistryBuilder.create().register("ignoreCookies", ignoreSpecProvider).build();
            HttpHost proxy = null;
            RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(Long.valueOf(10000L).intValue()).setSocketTimeout(Long.valueOf(60000L).intValue()).setConnectionRequestTimeout(Long.valueOf(60000L).intValue()).setProxy((HttpHost)proxy).build();
            HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pHCCM).setDefaultRequestConfig(clientConfig).setSchemePortResolver(new DefaultSchemePortResolver()).setDnsResolver(systemDefaultDnsResolver).setRequestExecutor(REQUEST_EXECUTOR).setDefaultCookieSpecRegistry(registry1).setDefaultSocketConfig(SocketConfig.DEFAULT).setRedirectStrategy(new LaxRedirectStrategy()).setConnectionTimeToLive(2000L, TimeUnit.MILLISECONDS).setRetryHandler(new StandardHttpRequestRetryHandler(0, false)).setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE);
            httpClient = builder.build();
        return httpClient;
    }

第四步:接下来你就可以使用返回的 client 去请求啦!~

注意:如果你是使用 Unirest,那恭喜你,你的使用方式非常简洁

Unirest.config()
  .clientCertificateStore("这里是我们存放p12证书的路径", "这里是证书的密码,如果没有密码则为空字符串");

Unirest.get("https://some.custom.secured.place.com")
                .asString();


↙↙↙阅读原文可查看相关链接,并与作者交流