簡體   English   中英

了解Apache HttpClient(Java)中的SSL

[英]Understanding SSL in Apache HttpClient (Java)

這里有一個自定義SSL的示例:
https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class ClientCustomSSL {

public final static void main(String[] args) throws Exception {
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
                    new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[] { "TLSv1" },
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();
    try {

        HttpGet httpget = new HttpGet("https://httpbin.org/");

        System.out.println("Executing request " + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
}

為什么我們需要那個? 我已經測試了沒有任何SSL內容的HttpClient請求,並且從HTTPS URL得到了正確的響應,沒有錯誤。
如果我不添加任何SSLContext,會有什么問題?
如果重要的是使其更加安全,那么這行是什么?:

.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),

似乎我們需要一些文件和一些密碼?

如果您不指定(使用工廠)上下文,則Java(JSSE)使用包含默認信任庫的默認上下文,該默認信任庫默認為文件JRE/lib/security/cacerts (或jssecacerts如果存在),除非被系統屬性覆蓋; 請參閱https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#CustomizingStores 根據您使用的是Oracle-was-Sun Java軟件包,IBM還是Apple軟件包,Android系統還是OpenJDK,此默認信任庫通常包含與大多數OS和瀏覽器(如 Verisign Symantec) 大致相同的公共CA集。 Digicert和GoDaddy以及LetsEncrypt / Identrust。 是否選擇默認的cacerts“安全”是您要做出的選擇。 如果不是,則可以更改默認文件的內容,或者讓代碼使用其他文件,如果要使用其他文件,則必須指定密鑰庫文件的文件名及其密碼。

該示例使用自定義存儲,因為它是自定義SSL的示例。 如果使用默認值,則它將是默認SSL的示例,而不是自定義SSL的示例。 對於許多實際應用程序,使用默認值就可以了。

除了: 指定TLSv1用於協議(意味着1.0)是方式過時,並且可能被認為是不安全的或至少邊界線。 實際上,它並沒有像SSLv3(和很久以前的SSLv2)那樣被徹底打破,因為BEAST被證明比人們想象的要溫和得多,但是TLSv1.1和1.2現在得到了廣泛的實現和使用,而1.3希望距離不太遠,因此廣泛使用1.0從上周末開始,禁止將TLSv1.0視為適用於許多人的不合標准的示例,並且該協議非常適用於許多人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM