0

I am trying to create an SSL HTTP client (to send data over TLS) with custom trust store and client store certificates. I was able to do this in Java via OKHTTP, but I am confused how I can do this in C#/.net

Here is OKHTTP approach I used:

byte[] trustStoreBytes = ...
byte[] clientCertBytes = ...

TrustManagerFactory trustManagerFactory = null;
try
{
    trustManagerFactory = createTrustManagerFactory(trustStoreBytes, trustStorePass);
}
catch (Exception e)
{
    Log.e(TAG, "Exception initializing TrustManagerFactory.", e);
}
if (trustManagerFactory == null)
{
    Log.e(TAG, "TrustManagerFactory cannot be null.");
}

SSLContext sslContext = null;
try
{
    sslContext = createSSLContext(clientCertBytes, clientCertPass, trustManagerFactory);
}
catch (Exception e)
{
    Log.e(TAG, "Exception initializing SSLContext.", e);
}
if (sslContext == null)
{
    Log.e(TAG, "SSLContext cannot be null.");
}

SSLSocketFactory sslSocketFactory = null;
X509TrustManager trustManager = null;
try
{
    sslSocketFactory = sslContext.getSocketFactory();
    trustManager = getX509TrustManager(trustManagerFactory);

    Log.d(TAG, "newSecureWebSocketsClient: " + sslSocketFactory.getDefaultCipherSuites().toString());
}
catch (Exception e)
{
    Log.e(TAG, "Unable to create ssl socket factory or trust manager.", e);
}
if (sslSocketFactory == null)
{
    Log.e(TAG, "SSL Socket Factory cannot be null.");
}
if (trustManager == null)
{
    Log.e(TAG, "Trust manager cannot be null");
}

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
clientBuilder.retryOnConnectionFailure(true);
clientBuilder.hostnameVerifier(new HostnameVerifier() {
                @Override

                public boolean verify(String hostname, SSLSession session)
{
    Log.i(TAG, "Hostname: " + hostname);
    Log.w(TAG, "Hostname verification is disabled. If you are using DNS," +
            " this could introduce security risks for you.");
    return true;
}
            });

return clientBuilder.build();

Here is my initial attempt with System.Net.Http.HTTPClient

HttpClient client = new HttpClient();
WebRequestHandler handler = new WebRequestHandler();
    
X509Certificate2 cert = new X509Certificate2(clientBytes, "password");
handler.ClientCertificates.Add(cert);
handler.ClientCertificates.Add( ??? );

I could add a trust store certificate to the ClientCertificates but that seems wrong. What is the right approach here? Thanks!

Airn5475
  • 2,452
  • 29
  • 51

0 Answers0