2012-10-12 252 views
5

我正在嘗試使用客戶端證書進行使用MonoTouch的SSL連接。似乎有幾個例子可以使用objective-c來做到這一點,我正在尋找的解決方案可能類似於回答here,但在MonoTouch(C#)中。帶有Monotouch的HTTPS客戶端證書

我在MonoTouch中使用了NSUrlConnection類,並且重寫了NSUrlConnectionDelegate類來響應身份驗證質詢。

我已經能夠從文件加載證書,但是我一直無法找到證書的有用表示來響應身份驗證質詢。

public override void ReceivedAuthenticationChallenge(NSUrlConnection connection, NSUrlAuthenticationChallenge challenge) 
{ 
    if (string.Equals(challenge.ProtectionSpace.AuthenticationMethod, "NSURLAuthenticationMethodClientCertificate", StringComparison.OrdinalIgnoreCase)) { 
     string password = "<password_signed_certificate>"; 
     byte[] data = File.ReadAllBytes("<path_of_file_in_ios_sandboxed_filesystem_pkcs>"); 
     NSDictionary opt = NSDictionary.FromObjectsAndKeys(new object[]{password}, new object[]{"passphrase"}); 
     NSDictionary[] items; 
     SecStatusCode stat = SecImportExport.ImportPkcs12(data, opt, out items); // Uses MonoTouch.Security namespace 
     MonoTouch.Security.SecTrust trust = (MonoTouch.Security.SecTrust)items[0]["trust"]; 
     // Everything to this point works, and I can inspect the trust object that all the expected certificate properties (IssuerName etc.) are correct 

     IntPtr secTrustRef = trust // ????? How do I bridge this gap 
     // NSUrlConnection does not utilise MonoTouch security namespace 

     NSUrlCredential cred = new NSUrlCredential(secTrustRef, true); 
     challenge.Sender.UseCredentials(cred, challenge); 
    } 
} 

一些注意事項:

  1. 我已經看到了Objective-C的解決方案,但我還沒有找到等效的一組中的MonoTouch(C#)所需的步驟。
  2. 我無法利用HttpWebRequest,因爲httpWebRequest.ClientCertificates(一個集合)的monotouch實現會引發「未實現的異常」。
  3. 我也試圖使用Mono.Security.X509和System.Security.Cryptography.X509Certificates命名空間來打開成功的證書,但我無法利用類實例來響應身份驗證挑戰,因爲我需要創建一個只接受IntPtr的NSUrlCredential對象。請參閱this

回答

1

使用HttpWebRequest的。在問題註釋2中,我說HttpWebRequest.ClientCertificates屬性拋出一個未實現的異常,因此我排除了這個選項。如果您嘗試使用新集合將其設置爲屬性,它會執行此操作,但如果您只是使用Get訪問器,則可以向集合中添加客戶端證書。

作爲一個方面說明,使用HttpWebRequest使應用程序更易於傳輸到其他設備,這是我們使用MonoDevelop如此雙贏的原因之一。

+0

關於如何使用NSUrlSession工作的任何想法? – nhenrique

2

我沒有一臺服務器的環境設置來嘗試這一點,但試試這個:

替換:

... 
MonoTouch.Security.SecTrust trust = (MonoTouch.Security.SecTrust)items[0]["trust"]; 
IntPtr secTrustRef = trust 
... 

有:

... 
NSObject obj = items[0]["trust"]; 
IntPtr secTrustRef = obj.Handle; 
... create and use your credentials 
GC.KeepAlive (obj); // just in case ;-) 
... 
+0

謝謝:)這讓我經歷瞭如何獲得句柄的問題,並因此得到了'接受的答案'。不幸的是,請求仍然失敗,(即使將證書作爲iPhone配置文件的一部分安裝在使用連接到該網站的Safari上的工作)。我還沒有看到有人使用MonoTouch和客戶端證書成功。只是希望我做一些愚蠢的事情,而不是說它根本不可能/不被支持。將繼續研究。感謝幫助。 – Bruce