[Android]一个通过Https的SSL验证的工具类

        在家休息了一个星期了,总结总结以前写过的代码,整理成工具,说不定以后用得上。

        废话不多说,直接上代码:

import android.content.Context;

import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

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

/**
 * create by yinyuan
 * 通过Https的SSL验证
 */
public class HTTPSTrustManager implements X509TrustManager {
    private static TrustManager[] trustManagers;
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

    @Override
    public void checkClientTrusted(
            X509Certificate[] x509Certificates, String s)
            throws java.security.cert.CertificateException {
        // To change body of implemented methods use File | Settings | File
        // Templates.
    }

    @Override
    public void checkServerTrusted(
            X509Certificate[] x509Certificates, String s)
            throws java.security.cert.CertificateException {
        // To change body of implemented methods use File | Settings | File
        // Templates.
    }

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

    /**
     * 信任所有证书
     *
     * 使用示例:在所有https开始请求之前调用HTTPSTrustManager.allowAllSSL();
     */
    public static void allowAllSSL() {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                // TODO Auto-generated method stub
                return true;
            }

        });

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

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


    /**
     * 信任指定证书
     *
     * @param inputContext 上下文
     * @return
     *
     * 使用示例:先要获取到证书,我们可以放到assert目录下,例如这里使用的证书的文件名为“root.crt”。
     *          通过如下函数来读取,并返回SSLContext:然后,在使用 HttpsURLConnection 的过程中,
     *          也就是httpsPostData()函数中,使用指定证书的 SSLContext 即可:
     *          conn.setSSLSocketFactory(getSSLContext(context).getSocketFactory());
     */
    public static SSLContext getSSLContext(Context inputContext) {
        SSLContext context = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream in = inputContext.getAssets().open("root.crt");
            Certificate ca = cf.generateCertificate(in);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setCertificateEntry("ca", ca);
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keystore);
            // Create an SSLContext that uses our TrustManager
            context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return context;
    }
}

因为之前我们公司是没有证书的,所以用allowSSL的方式绕过认证,使用示例:

public class HttpsAuth implements Auth {

    private String sBaseEndpointUrl = "https://xxxxxxxxxxxxxxx";

    public void setsBaseEndpointUrl(String sBaseEndpointUrl) {
        this.sBaseEndpointUrl = sBaseEndpointUrl;
    }

    @Override
    public String getTokenFromCloud(LoggerHandler mLogger, String deviceId, String clientId) {
        if (clientId == null || clientId.isEmpty() || deviceId == null || deviceId.isEmpty()) {
            return null;
        }
        try {
            final JSONObject scopeData = new JSONObject();
            final JSONObject data = new JSONObject();
            final JSONObject productInstanceAttributes = new JSONObject();

            productInstanceAttributes.put("deviceSerialNumber", mProductDSN);
            data.put("productInstanceAttributes", productInstanceAttributes);
            data.put("productID", mProductID);
            scopeData.put("alexa:all", data);

            final String urlParameters = "response_type=device_code"
                    + "&client_id=" + clientId
                    + "&scope=" + sScopeValue
                    + "&scope_data=" + scopeData.toString();

            HttpsURLConnection con = null;
            DataOutputStream os = null;
            InputStream response = null;

            try {
                HTTPSTrustManager.allowAllSSL();
                URL obj = new URL(sBaseEndpointUrl);
                con = (HttpsURLConnection) obj.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json;charset=utf-8");

                String body = "{}";

                con.setDoOutput(true);
                os = new DataOutputStream(con.getOutputStream());
                os.writeBytes(body);


                int responseCode = con.getResponseCode();
                if (responseCode == sResponseOk) {
                    response = con.getInputStream();
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(response));
                    String inputLine;
                    StringBuilder result = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        result.append(inputLine);
                    }

                    return result.toString();
                } else {
                    mLogger.postError(sTag, "get Response error : errorCode = " + responseCode);
                }

            } catch (IOException e) {
                mLogger.postError(sTag, e.getMessage());
            } finally {
                if (con != null) con.disconnect();
                if (os != null) {
                    try {
                        os.flush();
                        os.close();
                    } catch (IOException e) {
                        mLogger.postWarn(sTag, "Cannot close resource. Error: "
                                + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            mLogger.postError(sTag, e.getMessage());
        }
        return null;
    }
}

        记录一下,希望以后用得到。

发布了61 篇原创文章 · 获赞 2 · 访问量 8710

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/100283250