我正在尝试通过我的Android客户端连接到我的服务器。服务器是HTTPS。为了使客户端连接到服务器,我使用了一个client.key和client.crt,它通过与服务器相同的CA .crt文件进行了签名,并转换为.p12格式。客户端应该具有私钥和公钥。但客户端不应该有服务器私钥。让Android工作的唯一方法是将p12文件从服务器加载到TrustManagerFactory
。但这不是正确的方法,因为来自服务器的私钥在该文件中。 TrustManagerFactory
不允许我加载.crt文件。
我的问题是:如何将.crt文件加载到KeyStore
而不是我现在使用的p12。或者我需要使用KeyStore
。
答案 0 :(得分:1)
Directly from google dev guide working solution for ya:
// 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);