我有一个小型的学校项目,我的老师要我做以下事情:
我唯一能找到的是如何完全验证证书,而不是如何逐步手动验证。
有人能指出我正确的方向吗? :)
提前致谢
答案 0 :(得分:2)
取决于您如何获得证书以及您想要验证的内容。无论是在SSL连接2way身份验证,客户端身份验证,还是只是您描述的步骤。
如果是HTTP连接,区别在于您可以获得证书(以及允许您执行此操作的方法),如果您不需要,只需跳到最后:
<强> HTTP 强> 这里很棘手,因为Android 6.0 Apache HTTP客户端已从Android SDK中删除,因此下面描述的所有信息都可能被弃用。但是,既然是学校的项目,你可以大致了解如何做到这一点: http://developer.android.com/intl/es/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
然而,
有一个名为X509HostnameVerifier
的界面
https://stuff.mit.edu/afs/sipb/project/android/docs/reference/org/apache/http/conn/ssl/X509HostnameVerifier.html
abstract boolean verify(String host, SSLSession session)
abstract void verify(String host, X509Certificate cert)
abstract void verify(String host, SSLSocket ssl)
abstract void verify(String host, String[] cns, String[] subjectAlts)
在这里,您可以访问服务器证书
OWN CERTIFICATE
问题是您希望如何为您的应用提供证书。有几种可能性:
以上三者几乎相同,因为从中检索X509Certificate
非常简单,你可以找到很多如何做的例子。
只要获得所需的X509Certificate对象:
1.您可以从X509Cert主体中提取它
2. checkValidity()
用于验证,getNotAfter()
getNotBefore()
方法用于确切日期
3. X509Certificate只能在签名者身上使用getIssuerX500Principal()
或getIssuerDn()
。如果你想上去,你需要证书链
答案 1 :(得分:0)
Official Android documentation give this:
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection =
(HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);
CHECK COMPLETE INFORMATION HERE