C#C
C#3y ago
pogrammerX

❔ C# Self Signed certificate with SslStream

My Code:
            var listener = new TcpListener(IPAddress.Any, 443); // Port 443 is typically used for HTTPS

            listener.Start();

            X509Certificate2 serverCertificate = new X509Certificate2("C:\\Users\\pogrammerX\\XXXXXXX\\XXXServer\\XXXServer\\bin\\Debug\\net6.0\\certificate.pfx", "password");

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                var client = listener.AcceptTcpClient();

                // Create an SSL stream using the client's network stream and the server certificate.
                var q = client.GetStream();
                var sslStream = new SslStream(q);
                sslStream.AuthenticateAsServer(serverCertificate, false, System.Security.Authentication.SslProtocols.Tls, true);

                Console.WriteLine("Connected!");

                byte[] buffer = new byte[client.ReceiveBufferSize];
                int bytesRead;

                while ((bytesRead = sslStream.Read(buffer, 0, client.ReceiveBufferSize)) > 0)
                {
                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received: " + message);
                }

                sslStream.Close();
                client.Close();
            }


Commands used to generate the self signed certificate:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt -subj "/C=US/ST=State/L=City/O=Organization/CN=127.0.0.1"
openssl pkcs12 -export -out certificate.pfx -inkey privatekey.key -in certificate.crt -passout pass:password


where this line:
sslStream.AuthenticateAsServer(serverCertificate, false, System.Security.Authentication.SslProtocols.Tls, true);

throws:
System.IO.IOException: 'Cannot determine the frame size or a corrupted frame was received.'

After further testing it seems like serverCertificate has some issues, any help is appreciated
Was this page helpful?