java - 如何在自签名服务器和客户端证书上调用 https get 方法

标签 java apache http https servlet-3.0

我已将 Apache tomcat 5 设置为支持 ssl。创建自签名证书并将客户端证书导入服务器的 trusstore 并将 p12 文件导入浏览器并访问 https 上的页面是可能的。如何使用 java 实现同样的效果?

以下是我正在尝试但没有成功的代码...

//reference  : http://vafer.org/blog/20061010073725/    http://www.mkyong.com/java/java-//https-client-httpsurlconnection-example/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.security.cert.Certificate;






public class HttpClientTutorial {

    @SuppressWarnings("unused")
    private static javax.net.ssl.SSLSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException  
    {
          KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
          KeyStore keyStore = KeyStore.getInstance("PKCS12");

          InputStream keyInput = new FileInputStream(pKeyFile);
          keyStore.load(keyInput, pKeyPassword.toCharArray());
          keyInput.close();

          keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

          SSLContext context = SSLContext.getInstance("TLS");
          context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

          return context.getSocketFactory();
    }

       private static void print_https_cert(HttpsURLConnection con){

            if(con!=null){

              try {

            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            Certificate[] certs = con.getServerCertificates();
            for(Certificate cert : certs){
               System.out.println("Cert Type : " + cert.getType());
               System.out.println("Cert Hash Code : " + cert.hashCode());
               System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
               System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
               System.out.println("\n");
            }

            } catch (SSLPeerUnverifiedException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }

             }

           }

           private static void print_content(HttpsURLConnection con){
            if(con!=null){

            try {

               System.out.println("****** Content of the URL ********");            
               BufferedReader br = 
                new BufferedReader(
                    new InputStreamReader(con.getInputStream()));

               String input;

               while ((input = br.readLine()) != null){
                  System.out.println(input);
               }
               br.close();

            } catch (IOException e) {
               e.printStackTrace();
            }

               }

           }


    public static void main(String[] args) throws IOException, UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
        URL url = new URL("https://localhost:8443/SpringSec2");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(getFactory(new File("src/Client.p12"), "client"));

          //dumpl all cert info
         print_https_cert(con);

         //dump all the content
         print_content(con);


    }



}


***************************************************************************************

异常(exception):

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)

最佳答案

由于您使用的是自签名证书,因此您需要提供自己的 TrustManager。您代码中的行

SSLContext 上下文 = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

context.init 中的第二个参数是 TrustManager,用于管理您可以信任的服务器。您基本上需要创建自己的扩展 X509TrustManager。该代码的示例可以在 http://www.howardism.org/Technical/Java/SelfSignedCerts.html 找到.搜索 NaiveTrustManager,您会看到 checkServerTrusted() 未实现,这意味着它信任所有内容。首先尝试一下,看看是否可行。完成后,您可能需要考虑实现更严格的检查。

关于java - 如何在自签名服务器和客户端证书上调用 https get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10034369/

相关文章:

apache - Laravel SSL .htaccess 重定向到 index.php

java - Android MTP 客户端打开整个设备而不是单个界面

java - 我们可以用java读取swf文件吗?

java - JSP/Servlet 获取表单数据

apache - 在 Docker 容器上启动 Apache

rest - 拒绝不受支持的 API 客户端时的 HTTP 状态代码

java - 只是想知道 spring mvc 与 django 之间的区别

apache - cxf 故障转移恢复

http - 来自同一 session 的多个请求如何始终落在同一台服务器上?

rest - 如何使用http实现竞争消费者