Java使用个人SSL证书

接受指定网站的SSL证书.

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
...

    public static void testHttpHead() throws Exception {
        // load certificate
        // in firefox, Export as (type X.509 Certificate (PEM))
        InputStream trustStore = new BufferedInputStream(
                new FileInputStream("/home/gutsy/lib/vc.crt"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca = cf.generateCertificate(trustStore);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());

        // key store
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca",ca);

        // configure for self-signed ssl
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // ssl context
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        SSLSocketFactory sslFactory = ctx.getSocketFactory();



        // download checksum is case-sensitive
        String checksum = "1ccd9f3dff172ef4fa1cb3dc437981d3";
        URL url = new URL("https://files.test.com/chatfile/"+checksum);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();

        urlConn.setSSLSocketFactory(sslFactory); // use our ssl factory
        urlConn.setRequestMethod("HEAD");

        System.out.println("Response HTTP status: "+urlConn.getResponseCode());

        Map<String, List<String>> headers = urlConn.getHeaderFields();
        System.out.println(headers);

        urlConn.disconnect();
    }






你可能感兴趣的:(Java使用个人SSL证书)