title: How to create ssl context with HTTP Client with custom trust store and client store certificates?
body: <p>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</p>
  <p>Here is OKHTTP approach I used:</p>
  <pre><code>byte[] trustStoreBytes = ...
  byte[] clientCertBytes = ...
  
  TrustManagerFactory trustManagerFactory = null;
  try
  {
      trustManagerFactory = createTrustManagerFactory(trustStoreBytes, trustStorePass);
  }
  catch (Exception e)
  {
      Log.e(TAG, &quot;Exception initializing TrustManagerFactory.&quot;, e);
  }
  if (trustManagerFactory == null)
  {
      Log.e(TAG, &quot;TrustManagerFactory cannot be null.&quot;);
  }
  
  SSLContext sslContext = null;
  try
  {
      sslContext = createSSLContext(clientCertBytes, clientCertPass, trustManagerFactory);
  }
  catch (Exception e)
  {
      Log.e(TAG, &quot;Exception initializing SSLContext.&quot;, e);
  }
  if (sslContext == null)
  {
      Log.e(TAG, &quot;SSLContext cannot be null.&quot;);
  }
  
  SSLSocketFactory sslSocketFactory = null;
  X509TrustManager trustManager = null;
  try
  {
      sslSocketFactory = sslContext.getSocketFactory();
      trustManager = getX509TrustManager(trustManagerFactory);
  
      Log.d(TAG, &quot;newSecureWebSocketsClient: &quot; + sslSocketFactory.getDefaultCipherSuites().toString());
  }
  catch (Exception e)
  {
      Log.e(TAG, &quot;Unable to create ssl socket factory or trust manager.&quot;, e);
  }
  if (sslSocketFactory == null)
  {
      Log.e(TAG, &quot;SSL Socket Factory cannot be null.&quot;);
  }
  if (trustManager == null)
  {
      Log.e(TAG, &quot;Trust manager cannot be null&quot;);
  }
  
  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, &quot;Hostname: &quot; + hostname);
      Log.w(TAG, &quot;Hostname verification is disabled. If you are using DNS,&quot; +
              &quot; this could introduce security risks for you.&quot;);
      return true;
  }
              });
  
  return clientBuilder.build();
  </code></pre>
  <p>Here is my initial attempt with <code>System.Net.Http.HTTPClient</code></p>
  <pre><code>HttpClient client = new HttpClient();
  WebRequestHandler handler = new WebRequestHandler();
      
  X509Certificate2 cert = new X509Certificate2(clientBytes, &quot;password&quot;);
  handler.ClientCertificates.Add(cert);
  handler.ClientCertificates.Add( ??? );
  </code></pre>
  <p>I <em>could</em> add a trust store certificate to the ClientCertificates but that seems wrong. What is the right approach here? Thanks!</p>