TLS and HTTPS

suggest change

Transport Layer Security (TLS 1.2 and TLS 1.3) provides end-to-end encryption, authentication, and data integrity over TCP networks. In .NET, TLS is used across high-level HTTP clients (HttpClient), low-level secure socket streams (SslStream), and web servers (Kestrel).


1. Secure HTTPS Requests with HttpClient

Modern .NET uses SocketsHttpHandler by default, negotiating the highest available TLS version (TLS 1.2 or TLS 1.3) supported by the operating system.

Basic HTTPS Request

using System;
using System.Net.Http;
using System.Threading.Tasks;

using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("my-app/1.0"); // GitHub API rejects requests without a User-Agent
string content = await client.GetStringAsync("https://api.github.com");
Console.WriteLine(content);

Mutual TLS (mTLS) with Client Certificates

When an API requires the client to authenticate itself with an X.509 certificate:

using System.Net.Http;
using System.Security.Cryptography.X509Certificates;

// Load client certificate (from PFX file or Windows Certificate Store)
using var clientCertificate = X509CertificateLoader.LoadPkcs12FromFile("client-cert.pfx", "certPassword");

var handler = new SocketsHttpHandler();
handler.SslOptions.ClientCertificates = new X509CertificateCollection { clientCertificate };

using var httpClient = new HttpClient(handler);
HttpResponseMessage response = await httpClient.GetAsync("https://secure-api.internal.bank.com/data");

Custom Certificate Validation (Development / Pinning)

For development against self-signed certificates or implementing certificate pinning:

var handler = new SocketsHttpHandler
{
    SslOptions =
    {
        RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
        {
            // WARNING: Dangerous for production if blindly returning true!
            // In production, validate specific thumbprints or custom CA chains:
            if (certificate != null && certificate.GetCertHashString() == "EXPECTED_THUMBPRINT_HEX")
            {
                return true;
            }

            // Fallback to standard OS validation
            return sslPolicyErrors == System.Net.Security.SslPolicyErrors.None;
        }
    }
};

using var client = new HttpClient(handler);

2. Low-Level Secure TCP Communication with SslStream

When communicating over non-HTTP protocols (e.g., custom binary protocols, SMTP, or IRC), wrap a NetworkStream with System.Net.Security.SslStream.

TLS Client Example

using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;

class SecureTcpClient
{
    static async Task Main()
    {
        string host = "www.google.com";
        int port = 443;

        using var tcpClient = new TcpClient();
        await tcpClient.ConnectAsync(host, port);

        // Wrap the network stream in an SslStream
        using var sslStream = new SslStream(
            tcpClient.GetStream(),
            leaveInnerStreamOpen: false,
            userCertificateValidationCallback: (sender, cert, chain, errors) => errors == SslPolicyErrors.None
        );

        // Perform TLS handshake
        await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions
        {
            TargetHost = host,
            EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
        });

        Console.WriteLine($"[Connected] Protocol: {sslStream.SslProtocol}, Cipher: {sslStream.NegotiatedCipherSuite}");

        // Send raw HTTP GET request over encrypted TLS tunnel
        byte[] request = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
        await sslStream.WriteAsync(request);
        await sslStream.FlushAsync();

        // Read response
        byte[] buffer = new byte[2048];
        int bytesRead = await sslStream.ReadAsync(buffer);
        string responseText = Encoding.UTF8.GetString(buffer, 0, bytesRead);

        Console.WriteLine("Response headers preview:\n" + responseText.Split("\r\n\r\n")[0]);
    }
}

3. Loading Certificates from the Windows Store

using System.Security.Cryptography.X509Certificates;

X509Certificate2? FindCertificateBySubject(string subjectName)
{
    using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);

    var certs = store.Certificates.Find(
        X509FindType.FindBySubjectName,
        subjectName,
        validOnly: true
    );

    return certs.Count > 0 ? certs[0] : null;
}

4. Programmatically Generating Self-Signed Certificates (Testing)

In modern .NET (.NET Core 2.0+), you can generate valid self-signed certificates without external tools like OpenSSL or Makecert:

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

X509Certificate2 GenerateSelfSignedCertificate(string hostname)
{
    using var rsa = RSA.Create(keySizeInBits: 2048);
    var request = new CertificateRequest(
        $"CN={hostname}",
        rsa,
        HashAlgorithmName.SHA256,
        RSASignaturePadding.Pkcs1
    );

    // Subject Alternative Name (SAN)
    var sanBuilder = new SubjectAlternativeNameBuilder();
    sanBuilder.AddDnsName(hostname);
    sanBuilder.AddDnsName("localhost");
    request.CertificateExtensions.Add(sanBuilder.Build());

    // Basic usage constraints
    request.CertificateExtensions.Add(
        new X509EnhancedKeyUsageExtension(
            new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, // Server Authentication
            false
        )
    );

    DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddMinutes(-5);
    DateTimeOffset notAfter = DateTimeOffset.UtcNow.AddYears(1);

    // Self-sign with private key
    using X509Certificate2 cert = request.CreateSelfSigned(notBefore, notAfter);

    // Export and reload so private key is exportable/usable by SslStream or Kestrel
    return X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pfx, "tempPass"), "tempPass", X509KeyStorageFlags.Exportable);
}

5. Security Best Practices

  1. Never Disable Certificate Validation Globally: Avoid ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;. This opens the application to Man-in-the-Middle (MITM) attacks.
  2. Disallow Legacy Protocols: Ensure deprecated protocols (Ssl3, Tls, Tls10, Tls11) are disabled; enforce Tls12 and Tls13.
  3. Always Dispose Certificates: X509Certificate2 encapsulates unmanaged cryptographic key handles. Always wrap instances in using statements or call .Dispose().
  4. Use System Certificate Store: In containerized Linux and Windows environments, install custom root CAs into the operating system trust store rather than bypassing validation callbacks in C# code.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents