使用 Xamarin 与客户端证书进行 SSL 通信 Android

SSL Communication with Client Certificate using Xamarin Android

我正在创建一个企业应用程序,其中组织的 MDM 解决方案将在设备上安装客户端证书。我使用下面的代码绑定读取相同内容,但我的连接未与服务器建立。

if (x is X509Certificate[] certificates && y is IPrivateKey privateKey)
{
    var keyStore = KeyStore.GetInstance("PKCS12");
    keyStore.Load(null, null);
    var keyFactory = KeyFactory.GetInstance(privateKey?.Algorithm);

    keyStore.SetKeyEntry(alias, privateKey, null, certificates);
    var kmf = KeyManagerFactory.GetInstance(KeyManagerFactory.DefaultAlgorithm);
    kmf.Init(keyStore, null);

    var sslContext = SSLContext.GetInstance("TLS");
    sslContext.Init(kmf.GetKeyManagers(), null, null);

    var sslSocketFactory = sslContext.SocketFactory;
    var sslSocket = (SSLSocket)sslSocketFactory.CreateSocket(new Socket(hostName, port), hostName, port, false);
    sslSocket.AddHandshakeCompletedListener(new HandshakeCompletedListener());
    sslSocket.NeedClientAuth = true;
    sslSocket.KeepAlive = true;
    sslSocket.StartHandshake();
    var uri = new URL("https://apiapp-iserver.ase-meap-dev.p.azurewebsites.net/api/CertificateLogin");
    var urlConnection = (HttpsURLConnection)uri.OpenConnection();

    var status = urlConnection.ResponseCode;
    if (status == HttpStatus.Forbidden)
    {
        var errorStream = urlConnection.ErrorStream;
        var errorResult = ReadStream(errorStream);
    }
    urlConnection.SSLSocketFactory = sslContext.SocketFactory;
    var inputStream = urlConnection.InputStream;
    var loResponseStream = new StreamReader(inputStream);
    var response = loResponseStream.ReadToEnd();
}   

我正在使用下面的代码来读取私钥和证书。

private X509Certificate[] GetCertificates(string alias)
{
    try
    {
        return KeyChain.GetCertificateChain(RootActivity, alias);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    return null;
}
private IPrivateKey GetPrivateKey(string alias)
{
    try
    {
        return KeyChain.GetPrivateKey(RootActivity, alias);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
    return null;

}

我也通过使用 OnReceivedClientCertRequest 传递证书和密钥对 WebView 进行了相同的尝试,并且工作正常。

 public override void OnReceivedClientCertRequest(WebView view, ClientCertRequest request)
 {
     request.Proceed(PPritvateKey, CCertificate);
 }

你能帮我找出我的代码有什么问题吗?

您可以使用 URLConnection.Connect Method() 打开与资源的连接。

urlConnection.Connect();

更多信息,请参考下面的link。

URLConnection.Connect 方法: https://docs.microsoft.com/en-us/dotnet/api/java.net.urlconnection.connect?view=xamarin-android-sdk-9#Java_Net_URLConnection_Connect

URL.openConnection 例子: https://csharp.hotexamples.com/examples/-/URL/openConnection/php-url-openconnection-method-examples.html

您尚未配置信任管理器工厂以及影响请求调用的实习生。试试这个

if (x is X509Certificate[] certificates && y is IPrivateKey privateKey)
{
    var keyStore = KeyStore.GetInstance("PKCS12");
    keyStore.Load(null, null);
    var keyFactory = KeyFactory.GetInstance(privateKey?.Algorithm);

    keyStore.SetKeyEntry(alias, privateKey, null, certificates);
    var kmf = KeyManagerFactory.GetInstance(KeyManagerFactory.DefaultAlgorithm);
    kmf.Init(keyStore, null);

    KeyStore serverKeysStore = KeyStore.GetInstance("AndroidCAStore");
    serverKeysStore.Load(null, null);

    var serverTrustManagerFactory = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm);
    serverTrustManagerFactory.Init(serverKeysStore);
    var tms = serverTrustManagerFactory.GetTrustManagers();

    var sslContext = SSLContext.GetInstance("TLS");
    sslContext.Init(kmf.GetKeyManagers(), serverTrustManagerFactory.GetTrustManagers(), new SecureRandom());
    HttpsURLConnection.DefaultSSLSocketFactory = sslContext.SocketFactory;
    var sslSocketFactory = sslContext.SocketFactory;
    var sslSocket = (SSLSocket)sslSocketFactory.CreateSocket(new Socket(hostName, port), hostName, port, false);
    sslSocket.AddHandshakeCompletedListener(new HandshakeCompletedListener());
    sslSocket.NeedClientAuth = true;
    sslSocket.KeepAlive = true;
    sslSocket.StartHandshake();
    var uri = new URL("https://apiapp-iserver.ase-meap-dev.p.azurewebsites.net/api/CertificateLogin");
    var urlConnection = (HttpsURLConnection)uri.OpenConnection();

    var status = urlConnection.ResponseCode;
    if (status == HttpStatus.Forbidden)
    {
        var errorStream = urlConnection.ErrorStream;
        var errorResult = ReadStream(errorStream);
    }
    urlConnection.SSLSocketFactory = sslContext.SocketFactory;
    var inputStream = urlConnection.InputStream;
    var loResponseStream = new StreamReader(inputStream);
    var response = loResponseStream.ReadToEnd();
}