簡體   English   中英

使用.crt而不是.p12

[英]Using .crt instead of a .p12

我正在嘗試通過Android客戶端與服務器建立連接。 服務器是HTTPS。 為了使客戶端連接到服務器,我使用了client.key和client.crt,它們通過與服務器相同的CA .crt文件簽名,並轉換為.p12格式。 客戶端應該具有私鑰和公鑰。 但是客戶端不應具有服務器私鑰。 使Android正常工作的唯一方法是將p12文件從服務器加載到TrustManagerFactory 但這不是正確的方法,因為來自服務器的私鑰位於該文件內部。 TrustManagerFactory不允許我加載.crt文件。

我的問題是:如何將.crt文件加載到KeyStore而不是現在使用的p12中。 還是我需要使用KeyStore之后的其他東西。

直接從谷歌開發者指南為雅工作解決方案:

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM