2013年8月2日 星期五

for android ,accept ssl (any host)

1.u need a trust manager
===================code====================
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import javax.net.ssl.SSLSession;



public class _FakeX509TrustManager implements X509TrustManager {

    private static TrustManager[] trustManagers;
    private static final X509Certificate[] _AcceptedIssuers = new
X509Certificate[] {};

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String
authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String
authType) throws CertificateException {
    }

    public boolean isClientTrusted(X509Certificate[] chain) {
            return true;
    }

    public boolean isServerTrusted(X509Certificate[] chain) {
            return true;
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
            return _AcceptedIssuers;
    }

    public static void allowAllSSL() {
            HttpsURLConnection.setDefaultHostnameVerifier(
            new HostnameVerifier(){
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                            return true;
                    }

            });

            SSLContext context = null;
            if (trustManagers == null) {
                    trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
            }

            try {
                    context = SSLContext.getInstance("TLS");
                    context.init(null, trustManagers, new SecureRandom());
            } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
            } catch (KeyManagementException e) {
                    e.printStackTrace();
            }

   
   HttpsURLConnection.setDefaultSSLSocketFactory(
  context.getSocketFactory());
    }
}
====================================================
2nd,u need a  SSL socket factory:
================code=====================================
import android.net.SSLCertificateSocketFactory;
import android.net.SSLSessionCache;
import android.os.Build;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.params.HttpParams;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

public class NeoTechSSLSocketFactory extends SSLSocketFactory{

    SSLContext sslContext = SSLContext.getInstance("TLS");

    public NeoTechSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);
        TrustManager tm=new _FakeX509TrustManager();
        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    public NeoTechSSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
       super(null);
       sslContext = context;
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}
=======================================
 3nd, u need create httpClient from the SSLSocketFacotry
======function  create HttpClient=======================
 private static HttpClient sslClient(HttpClient client) {
   try {
       X509TrustManager tm = new X509TrustManager() {
           public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
           }

           public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
           }

           public X509Certificate[] getAcceptedIssuers() {
               return null;
           }
       };
       SSLContext ctx = SSLContext.getInstance("TLS");
       ctx.init(null, new TrustManager[]{tm}, null);
       SSLSocketFactory ssf = new NeoTechSSLSocketFactory(ctx);
       ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
       ClientConnectionManager ccm = client.getConnectionManager();
       SchemeRegistry sr = ccm.getSchemeRegistry();
       sr.register(new Scheme("https", ssf, 443));
       return new DefaultHttpClient(ccm, client.getParams());
   } catch (Exception ex) {
       return null;
   }
}
====================================================
4th,now u can use it
=====================caller example==========================
     _FakeX509TrustManager.allowAllSSL();
HttpClient httpclient =  sslClient(new DefaultHttpClient());
   HttpPost httppost = new HttpPost("https://"+SERVER_ADDRESS+destPath);
                            ....其他照舊....
=========================================================

沒有留言:

張貼留言