如何信任Android的SSL证书的PKCS12 [英] How to Trust Android SSL PKCS12 Certificate

查看:135
本文介绍了如何信任Android的SSL证书的PKCS12的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的示例code ..

Here is my sample Code..

        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();
    }

我收到错误的不受信任的服务器证书

I am getting Error as Not Trusted server Certificate

然而,如果我尝试在Java核心与相同的:
TMF的KeyManagerFactory =的KeyManagerFactory
                    .getInstance(X.509);
它的工作有..

Whereas if i try same in core java with: KeyManagerFactory tmf = KeyManagerFactory .getInstance("X.509"); Its working there..

推荐答案

确定家伙,我公司成立只有Android支持BKS这里keyStore在完整的解决方案。

OK Guys I founded that android supports only BKS keyStore here is the complete solution

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();
    }
}

这篇关于如何信任Android的SSL证书的PKCS12的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆