我使用SSL與我的服務器通話,但擁有自簽名證書。如何在Xamarin.iOS和Universal Windows Platform中使用自簽名SSL證書?
在Android中我使用此代碼到我的SSL證書傳遞給系統能夠發出請求到我的服務器:
KeyStore ks = KeyStore.getInstance("BKS");
InputStream in = new ByteArrayInputStream(<byte [] my_ssl_data>);
ks.load(in, <string mypassword>.toCharArray());
in.close();
TrustManagerFactory Main_TMF = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
Main_TMF.init(ks);
X509TrustManager Cur_Trust_Manager = new X509TrustManager()
{
public void checkClientTrusted(X509Certificate [] chain, String authType) throws CertificateException { }
public void checkServerTrusted(X509Certificate [] chain, String authType) throws CertificateException { }
public X509Certificate [] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { Cur_Trust_Manager }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
try
{
Cur_Trust_Manager.checkServerTrusted((X509Certificate []) session.getPeerCertificates(), session.getCipherSuite());
return true;
}
catch (Exception e) {}
return false;
}
});
現在我需要在Windows中通用的應用程序是這樣的8.1+(WINDOWS +的WindowsPhone)和iOS 7.0+。
對於網絡請求,我使用System.Net.Http.HttpClient,它與UWP和Xamarin.iOS一起使用。我從DER格式的服務器獲得證書,但仍無法向HttpClient添加處理程序。
Xamarin.iOS版本說 「未實現」
HttpClientHandler myHandler = new HttpClientHandler();
X509Certificate2 certificate = new X509Certificate2();
certificate.Import(my_cert_der_bytes);
myHandler.ClientCertificates.Add(certificate);
myHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
myHandler.AllowAutoRedirect = false;
HttpClient c = new HttpClient(myHandler);
....
UWP版本不幸的是(爲什麼地獄?)不知道X509Certificate2和所有的東西。我試圖使用WinRtHttpClientHandler,但不知道我應該在哪裏通過我的證書。我試圖跳過錯誤(開始工作),但這不是一個解決方案,因爲我不希望我的請求被重定向到另一個未被監控的服務器。
var filter = new HttpBaseProtocolFilter();
Certificate cer = new Certificate(my_cert_bytes.AsBuffer());
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
WinRtHttpClientHandler myHandler = new WinRtHttpClientHandler(filter);
HttpClient c = new HttpClient(myHandler);
....
我懷疑這是大多數indies的常見任務,certs很少用於測試和小應用程序。但是平臺開發者似乎很難完成任務。有沒有可靠的解決方案?
這不是一個解決方案,我的自簽名證書不是調試證書。我不想支付證書,並且希望在證書過期或證書頒發機構網站停機時避免出現問題 – Tertium