gpt4 book ai didi

java - Android 使用证书建立 HTTPSConnection

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:02 27 4
gpt4 key购买 nike

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

我应该怎么做才能只信任我想要的证书?我需要该证书的哪些信息以及我必须使用哪些信息才能获得该证书?

谢谢

最佳答案

如果您想自己处理验证,最简单的部分就是固定公钥。但是你必须考虑撤销,然后你的问题就开始了。

为什么不简单地使用设备信任的证书?

关于java - Android 使用证书建立 HTTPSConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36679745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com