我有以下的任务,什么时候要实现,但似乎没有一个好的方式在网上展示如何优雅地做它。(解决方案要么使用旧的HTTPClient,要么解决方案关系不大)有人能对此提供任何建议或解决方案吗?
给定一个url,我的应用程序需要获取相关的TLS服务器证书并执行以下任务。
certificate
HttpURLConnection和URLConnection似乎与我试图完成的任务有关,但不确定如何检索服务器证书。
我知道以下关于Android服务器证书的网站
http://www.normalesup.org/~george/articles/manual_https_cert_check_on_android.html
发布于 2021-09-17 12:06:23
结果表明,您可以使用getServerCertificates()检索证书链,该证书链是在启动HttpsURLConnection后获取的。TLS是由HttpsURLConnection实现的,这样您就可以确认证书是真实的,并且您与服务器的通信是保密的,数据完整性得到了维护。
public void verifyCertificate(View view) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("DEBUG", "Hello there");
try {
aFunctionWithCoolName("https://urlOfTheSiteYouWannaCheck.com");
Log.d("DEBUG", "Executed aFancyFunctionWithCoolName without any exceptions");
} catch (IOException e) {
e.printStackTrace();
Log.d("DEBUG", "IOException");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.d("DEBUG", "NoSuchAlgorithmException");
} catch (CertificateEncodingException e) {
e.printStackTrace();
Log.d("DEBUG", "CertificateEncodingException");
} catch (CertificateParsingException e) {
e.printStackTrace();
Log.d("DEBUG", "CertificateParsingException");
} catch (Exception e) {
Log.wtf("DEBUG", "Too sad, I don't know what is happening :(");
}
}
}).start();
}
private static void aFunctionWithCoolName(String httpsURL) throws IOException, NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
final HttpsURLConnection con = (HttpsURLConnection) (new URL(httpsURL)).openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.connect();
// https://developer.android.com/reference/java/security/cert/X509Certificate
// https://developer.android.com/reference/java/security/cert/Certificate
// https://developer.android.com/reference/javax/net/ssl/HttpsURLConnection#getServerCertificates()
final Certificate[] certs = con.getServerCertificates();
final Certificate subjectCert = certs[0];
final Certificate rootCert = certs[certs.length-1];
if (subjectCert instanceof X509Certificate && rootCert instanceof X509Certificate) {
X509Certificate sc = (X509Certificate) subjectCert;
X509Certificate rc = (X509Certificate) rootCert;
printX509CertificateDetail(sc);
}
}
public static void printX509CertificateDetail(X509Certificate cert) {
Log.d("DEBUG", "===========================================");
Log.d("DEBUG - Subject DN", cert.getSubjectX500Principal().toString());
Log.d("DEBUG - Subject CN", getSubjectCommonName(cert));
Log.d("DEBUG - URL DN", url.getHost());
Log.d("DEBUG - Issuer DN", cert.getIssuerDN().toString());
Log.d("DEBUG - Not After", cert.getNotAfter().toString());
Log.d("DEBUG - Not Before", cert.getNotBefore().toString());
}https://stackoverflow.com/questions/69208945
复制相似问题