Trusting all certificates using HttpClient over HTTPS

后端 未结 21 2287
北恋
北恋 2020-11-21 04:50

Recently posted a question regarding the HttpClient over Https (found here). I\'ve made some headway, but I\'ve run into new issues. As with my last problem, I

21条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:24

    This is a bad idea. Trusting any certificate is only (very) slightly better than using no SSL at all. When you say "I want my client to accept any certificate (because I'm only ever pointing to one server)" you are assuming this means that somehow pointing to "one server" is safe, which it's not on a public network.

    You are completely open to a man-in-the-middle attack by trusting any certificate. Anyone can proxy your connection by establishing a separate SSL connection with you and with the end server. The MITM then has access to your entire request and response. Unless you didn't really need SSL in the first place (your message has nothing sensitive, and doesn't do authentication) you shouldn't trust all certificates blindly.

    You should consider adding the public cert to a jks using keytool, and using that to build your socket factory, such as this:

        KeyStore ks = KeyStore.getInstance("JKS");
    
        // get user password and file input stream
        char[] password = ("mykspassword")).toCharArray();
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream stream = cl.getResourceAsStream("myjks.jks");
        ks.load(stream, password);
        stream.close();
    
        SSLContext sc = SSLContext.getInstance("TLS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    
        kmf.init(ks, password);
        tmf.init(ks);
    
        sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(),null);
    
        return sc.getSocketFactory();
    

    This has one caveat to watch out for. The certificate will expire eventually, and the code will stop working at that time. You can easily determine when this will happen by looking at the cert.

提交回复
热议问题