使用Monotouch的HTTPS客户端证书

Bru*_*uce 5 ssl-certificate nsurlconnection xamarin.ios ios

我正在尝试使用MonoTouch将客户端证书用于SSL连接.似乎有几个例子使用objective-c来做到这一点,我正在寻找的解决方案可能与此处回答的解决方案类似,但在MonoTouch(C#)中.

我在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);
   }
}
Run Code Online (Sandbox Code Playgroud)

一些说明:

  1. 我已经看到了Objective-c解决方案,但我没有找到MonoTouch(C#)所需的等效步骤集.
  2. 我不能利用HttpWebRequest,因为httpWebRequest.ClientCertificates(一个集合)的monotouch实现会抛出一个'not implemented exception'.
  3. 我还尝试使用Mono.Security.X509和System.Security.Cryptography.X509Certificates命名空间来成功打开证书,但我再次无法利用类实例来响应身份验证质询,因为我需要创建一个NSUrlCredential只接受IntPtr的对象.
  4. 另请参见.

Bru*_*uce 1

使用 HttpWebRequest。在问题注释第 2 点中,我说 HttpWebRequest.ClientCertificates 属性会引发未实现的异常,因此我排除了此选项。如果您尝试将其设置为新集合的属性,则确实如此,但如果您仅使用 Get 访问器,则可以将客户端证书添加到集合中。

附带说明一下,使用 HttpWebRequest 使应用程序更容易移植到其他设备,这也是我们使用 MonoDevelop 实现双赢的部分原因。