untrusted server cert chain issue

When reading the content from a HTTPS connection, a untrusted server cert chain can be thrown for untrusted servers. To force reading from such untrusted servers, this method installs a 'all-trustung' trust manager that returns 'true' for all servers. Just call this method and install a dummy host name verifier to read data from any uncertified server.
static public void trustHttpsCertificates() throws Exception {
        //Create a trust manager that does not validate certificate chains:
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
        //Install the all-trusting trust manager:
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        //SSLSocketFactory sf = sc.getSocketFactory();
        //avoid "HTTPS hostname wrong: should be <myhostname>" exception:
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                    System.out.println("Warning: URL host '"+urlHostName+"' is different to SSLSession host '"+session.getPeerHost()+"'.");
                return true; //also accept different hostname (e.g. domain name instead of IP address)

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.