簡體   English   中英

Android使用證書建立HTTPSConnection

[英]Android establish HTTPSConnection with certificate

我正在Android Studio下開發一個Android應用程序,我需要建立HTTPS連接。 到目前為止,我已經取得了成功,但在目前的實施中,我相信所有主機,這很容易導致中間人攻擊。 所以我想知道有沒有辦法相信一個確切的證書而不是其他的? 到目前為止我的代碼看起來像這樣:

    /**
* Trust every server - dont check for any certificate
*/
private void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[]{};
    }

    public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
    }
    }};

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我正在使用這樣的HttpsURLConnection

    private void postText(String URLAddress) {
    try {
        URL obj = new URL(URLAddress);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setHostnameVerifier(DO_NOT_VERIFY);
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            boolean First = true;
            while ((inputLine = in.readLine()) != null) {
                if(First)
                    First=false;
                else
                    response.append("\n");
                response.append(inputLine);
            }
            in.close();

            RequestResponse=response.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我該怎么做才能只信任我想要的證書? 我需要哪些信息才能獲得該證書?我必須使用哪些信息才能獲得該證書?

謝謝

如果您想自己處理驗證,那么簡單的部分就是固定公鑰。 但是你必須考慮撤銷,然后你的問題就開始了。

為什么不簡單地使用設備信任的證書?

我該怎么做才能只信任我想要的證書?

僅信任特定證書或公鑰的過程稱為證書鎖定或公鑰鎖定。 由於我不想重復已經存在的所有好信息:請轉到OWASP的特定文章,其中還包括Android的示例代碼 如果此鏈接發生故障或移動 - 只需搜索android證書固定示例

要做到這一點,正確的方法是驗證證書的主體身份作為被授權連接,而不是信任一個證書,除其他事項外給虐待你正在做認證過程的身份你在續訂時遇到問題。

在SSL級別,這是通過安裝握手偵聽器來完成的。

在HTTPS級別,這是通過安裝HostnameVerifier來完成的。

暫無
暫無

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

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