如何信任Android SSL PKCS12证书

时间:2011-02-26 12:53:54

标签: android

这是我的示例代码..

        System.setProperty("http.keepAlive", "false");
        HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname,
                            SSLSession session) {
                        // TODO Auto-generated method stub
                        return false;


        char[] passwKey = "pass".toCharArray();
        KeyStore ts = KeyStore.getInstance("PKCS12");

        InputStream in = getResources().openRawResource(
                R.raw.CertificateFile);
        ts.load(in, passwKey);
        KeyManagerFactory tmf = KeyManagerFactory
                .getInstance("X.509");
        tmf.init(ts, passwKey);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(tmf.getKeyManagers(),
                new X509TrustManager[] { new MyX509TrustManager(in,
                        "mobile".toCharArray()) }, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());

        URL url = new URL("https://url");
        HttpsURLConnection connection = (HttpsURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "params");
        connection.setRequestProperty("AppName", "params");
        connection.setRequestProperty("AppID",
                "params");

        BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String inputLine;

        while ((inputLine = bf.readLine()) != null) {
            txtMain.append("response " + inputLine + "\n");
            Log.d("@: ", inputLine);
        }
        in.close();

    } catch (Exception e) { // should never happen
        e.printStackTrace();
    }

我收到错误为不可信服务器证书

然而,如果我在核心java中尝试相同的: KeyManagerFactory tmf = KeyManagerFactory                     .getInstance( “X.509”); 它在那里工作..

2 个答案:

答案 0 :(得分:3)

OK Guys我发现android只支持BKS keyStore这里是完整的解决方案

try{

        System.setProperty("http.keepAlive", "false");
        HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {

                    public boolean verify(String hostname,
                            SSLSession session) {
                        return true;
                    }
                });

        char[] passwKey = "password".toCharArray();
        KeyStore ts = KeyStore.getInstance("BKS");
                InputStream in = getResources().openRawResource(
            R.raw.YOUR_CERTIFICATE_FILE);
                InputStream is = getResources().openRawResource(
            R.raw.YOUR_CERTIFICATE_FILE);
        ts.load(in, passwKey);
        KeyManagerFactory tmf = KeyManagerFactory.getInstance("X509");
        tmf.init(ts, passwKey);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(tmf.getKeyManagers(),
                new X509TrustManager[] { new MyX509TrustManager(is,
                        "password".toCharArray()) }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());

                URL url = new URL(Commons.ApiCall);

        HttpsURLConnection connection = (HttpsURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Username", Username);
        connection.setRequestProperty("Password", Password);

         BufferedReader bin = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

         StringBuffer sb = new StringBuffer();

        while ((line = bin.readLine()) != null) {
            sb.append(line);
        }


        in.close();  
                is.close();  
    } catch (Exception e) { // should never happen
        e.printStackTrace();
        Log.d("Err", e.toString());
    }

这是 MyX509TrustManager

public class MyX509TrustManager implements X509TrustManager {
    X509TrustManager pkixTrustManager;

    public MyX509TrustManager(InputStream trustStore, char[] password)
            throws Exception {
        // create a "default" JSSE X509TrustManager.

        KeyStore ks = KeyStore.getInstance("BKS");

        ks.load(trustStore, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);

        TrustManager tms[] = tmf.getTrustManagers();

        /*
         * Iterate over the returned trustmanagers, look for an instance of
         * X509TrustManager. If found, use that as our "default" trust manager.
         */
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                pkixTrustManager = (X509TrustManager) tms[i];
                return;
            }
        }

        /*
         * Find some other way to initialize, or else we have to fail the
         * constructor.
         */
        throw new Exception("Couldn't initialize");
    }

    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub
        try {
            pkixTrustManager.checkClientTrusted(arg0, arg1);
        } catch (CertificateException excep) {
            // do any special handling here, or rethrow exception.
        }

    }

    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub
        try {
            pkixTrustManager.checkServerTrusted(arg0, arg1);
        } catch (CertificateException excep) {
            /*
             * Possibly pop up a dialog box asking whether to trust the cert
             * chain.
             */
        }
    }

    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return pkixTrustManager.getAcceptedIssuers();
    }
}

答案 1 :(得分:0)

我相信这就是你所需要的:

Https Connection Android

相关问题