Skip to content

Instantly share code, notes, and snippets.

@rido-min
Created October 24, 2023 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rido-min/1644fc439e3b55b30e8cb0746ba1b5fd to your computer and use it in GitHub Desktop.
Save rido-min/1644fc439e3b55b30e8cb0746ba1b5fd to your computer and use it in GitHub Desktop.
SslStreamCustomCA
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
string host = "test.mosquitto.org";
int port = 8883;
using Socket socket = new(SocketType.Stream, ProtocolType.Tcp);
socket.Connect(host, port);
using NetworkStream stream = new(socket);
using SslStream sslStream = new(stream);
string ca = await new HttpClient().GetStringAsync("https://test.mosquitto.org/ssl/mosquitto.org.crt");
SslClientAuthenticationOptions tlsOps = new()
{
TargetHost = host
};
tlsOps.CertificateChainPolicy = new X509ChainPolicy();
tlsOps.CertificateChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
tlsOps.CertificateChainPolicy.CustomTrustStore.ImportFromPem(ca);
tlsOps.CertificateChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreEndRevocationUnknown;
sslStream.AuthenticateAsClient(tlsOps);
Console.WriteLine(sslStream.IsAuthenticated);
X509Certificate2 serverCert = new(sslStream.RemoteCertificate!);
Console.WriteLine($"TLS cert: \n\t {serverCert.Subject} from \n\t {serverCert.Issuer}");
foreach (X509Extension extension in serverCert.Extensions)
{
AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
Console.WriteLine("Extension type: {0}", extension.Oid.FriendlyName);
Console.WriteLine("Oid value: {0}", asndata.Oid.Value);
Console.WriteLine("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine);
Console.WriteLine(asndata.Format(true));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment