使用.crt而不是.p12
问题描述:
我想通过我的Android客户端连接到我的服务器。服务器是HTTPS。为了使客户端连接到服务器,我使用了一个client.key和client.crt,它通过与服务器相同的CA.crt文件进行签名,并转换为.p12格式。客户应该拥有私钥和公钥。但客户端不应该有服务器私钥。让Android工作的唯一方法是将p12文件从服务器加载到TrustManagerFactory
。但是这不是正确的方法,因为来自服务器的私钥在该文件内。 TrustManagerFactory
不允许我加载.crt文件。使用.crt而不是.p12
我的问题是:如何将.crt文件加载到KeyStore
而不是我现在使用的p12中。或者我需要使用其他的东西,然后KeyStore
。
答
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);
+0
谢谢,这正是我正在寻找的。 – Rockernaap
请阅读下面,看看它是否能帮助你或不http://stackoverflow.com/questions/32969952/android-to-server-communication-using-ssl-with-充气-城堡/ 32980130#32980130 – BNK
@BNK你的回答不会帮助他,因为他不希望加载'.p12'文件(因为包含在它的服务器私钥),他想用纯'.crt' 。而且没有任何信息如何仅用证书创建'Keystore',这样他就可以只运送'Keystore'。 – Than
@Than我的链接有两种选择:密钥库文件和证书文件。 – BNK