Android HttpsUrlConnection 验证 SSL

发布于 2024-12-14 05:16:56 字数 3060 浏览 2 评论 0原文

我有一个关于在 Android 中使用 HttpsUrlConnection 类 验证 SSL 的问题。我需要使用安全连接连接到 Web 服务器并验证 ssl。我必须检查它是否已过期,以及证书的名称是否与自定义名称匹配。 (可选)如果 SSL 证书缩略图也可以被验证(到预定义的),那就太好了。这是我现在用来连接到服务器的代码:

public void UseHttpsConnection(String url, String charset, String query) {

    try {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
            }
            @Override
            public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance( "TLS" );
        sslContext.init( null, trustAllCerts, new java.security.SecureRandom() );
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();



        System.setProperty("http.keepAlive", "false");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url)
                .openConnection();
        connection.setSSLSocketFactory( sslSocketFactory );
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    logOrIgnore.printStackTrace();
                }
        }

        int status = ((HttpsURLConnection) connection).getResponseCode();
        Log.i("", "Status : " + status);

        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.i("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }

        InputStream response = new BufferedInputStream(
                connection.getInputStream());

        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            handleDataFromSync(buffer2);
        }

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我在这里需要一些帮助,因为我对 SSL 验证及其基本操作很陌生。感谢您的任何帮助!

I have a question about validating SSL in Android using HttpsUrlConnection class. I need to connect to a web server using secure connection and validate the ssl. I have to check if it has expired or not, and also if the name of the certificate matches to a custom one. Optionally - it will be great if the SSL Certificate thumbnail can also be validated (to a predefined one). Here is the code which I'm using for now to connect to the server :

public void UseHttpsConnection(String url, String charset, String query) {

    try {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
            }
            @Override
            public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance( "TLS" );
        sslContext.init( null, trustAllCerts, new java.security.SecureRandom() );
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();



        System.setProperty("http.keepAlive", "false");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url)
                .openConnection();
        connection.setSSLSocketFactory( sslSocketFactory );
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    logOrIgnore.printStackTrace();
                }
        }

        int status = ((HttpsURLConnection) connection).getResponseCode();
        Log.i("", "Status : " + status);

        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.i("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }

        InputStream response = new BufferedInputStream(
                connection.getInputStream());

        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            handleDataFromSync(buffer2);
        }

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I need a little help here, because I'm new with SSL validation and the basic things to do with it. Thanks for any kind of help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云裳 2024-12-21 05:16:56

如果你想验证证书,你要做的第一件事就是扔掉那个信任任何东西的不安全的 TrustManager。相反,编写一个检查以您需要的方式收到的证书的证书。

If you want to validate the certificate the first thing you have to do is throw away that insecure TrustManager that trusts anything at all. Instead write one that checks the certificate received in the manner you require.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文