我正在尝试通过Android客户端与服务器建立连接。服务器是HTTPS。为了使客户端连接到服务器,我使用了client.key和client.crt,它们通过与服务器相同的CA .crt文件签名,并转换为.p12格式。客户端应该具有私钥和公钥。但是客户端不应具有服务器私钥。使Android正常工作的唯一方法是将p12文件从服务器加载到TrustManagerFactory中。但这不是正确的方法,因为来自服务器的私钥位于该文件内部。 TrustManagerFactory不允许我加载.crt文件。

我的问题是:如何将.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);

关于android - 使用.crt而不是.p12,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33415723/

10-13 03:01