簡體   English   中英

如何在Xamarin.iOS和通用Windows平台中使用自簽名SSL證書?

[英]How to use self-signed SSL certificate in Xamarin.iOS and 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 Universal App 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);
....

我懷疑這對於大多數獨立開發者來說是常見的任務,很少有證書用於測試和小型應用程序。 但是似乎平台開發人員很難完成任務。 有沒有可靠的解決方案?

UWP應用程序不能使用無效(和自簽名)證書。 您可以將Fiddler用作Fiddler的證書https的代理。

Telerik Fiddler選項-HTTPS-捕獲HTTPS連接。

該功能僅適用於台式機,而不適用於移動模擬器。

暫無
暫無

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

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