Hostname in certificate didn't match?

前端 未结 5 1099
挽巷
挽巷 2020-12-13 11:37

I try to connect to a server with a self-signed certificate. I use this code to accept all certificates.

public class CertificateAcceptor {

    public void          


        
相关标签:
5条回答
  • 2020-12-13 11:53

    The Answer by Prashant may not work, as you need to initialize the SSLContext as well.

    I would do it something like,

    SSLSocketFactory sf=null ;
            SSLContext sslContext = null;
            StringWriter writer;
            try {
                sslContext = SSLContext.getInstance("TLS")  ;
                sslContext.init(null,null,null);
            } catch (NoSuchAlgorithmException e) {
                //<YourErrorHandling>
            }  catch (KeyManagementException e){
                //<YourErrorHandling>
            }
    
            try{
                sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
            } catch(Exception e) {
                //<YourErrorHandling>
    
        }
            Scheme scheme = new Scheme("https",443,sf);
            httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
    
    0 讨论(0)
  • 2020-12-13 12:05

    My issue was, that Java SE 6 or smaller does not support SNI. That means, that one IP can only have one ssl cert. But on my server, there were 3 diffferent apis with different ssl certs. Java SE 7 or greater support SNI and everything worked just fine. (or only running one api on the server)

    0 讨论(0)
  • 2020-12-13 12:17

    ALLOW_ALL is not the correct answer. You should set up your certificate with the correct name by using keytool with the ext extension:

    keytool -genkeypair \
       -keystore keystore.jks \
      -dname "CN=OLEKSIYS-W3T, OU=Sun Java System Application Server, O=Sun Microsystems, L=Santa Clara, ST=California, C=US" \
      -keypass changeit \
      -storepass changeit \
      -keyalg RSA \
      -keysize 2048 \
      -alias default \
      -ext SAN=DNS:localhost,IP:127.0.0.1 \
      -validity 9999
    

    See http://tersesystems.com/2014/03/23/fixing-hostname-verification/ for more details.

    0 讨论(0)
  • 2020-12-13 12:19

    You may use SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER

    SSLSocketFactory sf = new SSLSocketFactory(
        SSLContext.getInstance("TLS"),
        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", 443, sf);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    
    HttpGet httpget = new HttpGet("https://host/");
    ...
    ...
    
    0 讨论(0)
  • 2020-12-13 12:19

    Have you tried calling setDefaultHostnameVerifier of HttpsURLConnection.

    See this link for an example: Accepting a certificate for HTTPs on Android

    0 讨论(0)
提交回复
热议问题