0

Никак не получается соединить даже 2 примера с msdn: https://msdn.microsoft.com/ru-ru/library/system.net.security.sslstream(v=vs.110).aspx

Вылетает на строчке

 sslStream.AuthenticateAsServer(serverCertificate, 
                false, SslProtocols.Tls, true);

Вот немного измененный код:

    using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Authentication.ExtendedProtection.Configuration;

namespace Examples.System.Net
{
    public sealed class SslTcpServer
    {
        static X509Certificate serverCertificate = null;
        public static void RunServer()
        {
            serverCertificate = new X509Certificate("my.pfx", "12345");
            TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1") , 5555);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient(TcpClient client)
        {
            SslStream sslStream = new SslStream(client.GetStream(), false);
            try
            {
                //sslStream.AuthenticateAsServer(certificate, true, SslProtocols.Ssl3, true)
                //sslStream.AuthenticateAsServer(serverCertificate,
                //    false, SslProtocols.Tls, true);
                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Default, true);
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);
                // Write a message to the client.
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }
        static string ReadMessage(SslStream sslStream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);
            return messageData.ToString();
        }
        public static int Main(string[] args)
        {
            SslTcpServer.RunServer();
            return 0;
        }
    }
}

На клиенте же:

   using System;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
            //Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            //return false;
        }
        public static void RunClient(string machineName, string serverName)
        {
            TcpClient client = new TcpClient(machineName, 5555);
            Console.WriteLine("Client connected.");
            SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate),  null);
            try
            {
                sslStream.AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            sslStream.Write(messsage);
            sslStream.Flush();
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
        private static void DisplayUsage()
        {
            Console.WriteLine("To start the client specify:");
            Console.WriteLine("clientSync machineName [serverName]");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            SslTcpClient.RunClient("127.0.0.1", "CEPO1701279874.cer");
            return 0;
        }
    }
}

Сама ошибка:

NotSupportedException не обработано: Дополнительные сведения: SSL серверного режима должен использовать сертификат с соответствующим частным ключом.

Как это решить?

P.S. Если есть у кого базовый рабочий пример, прошу поделиться.

2 ответа 2

2

Ошибка "SSL серверного режима должен использовать сертификат с соответствующим частным ключом." означает что вы попытались воспользоваться сертификатом без приватного ("частного") ключа.

Такое возможно в нескольких случаях:

  1. Это не ваш сертификат, и у вас нет ключа от него
  2. Вы потеряли приватный ключ в процессе преобразований формата сертификата
  3. Вы используете класс X509Certificate вместо X509Certificate2
0

Ну как что ему надо? Ему не нравится сертификат который вы сгененировали, возможно, отсутствует цепочка подлинности/корневой сертификат или ещё что-то.

Если бы вы внимательно посмотрели бы на свой код, то могли бы догадаться ВРЕМЕННО оставить в коде ValidateServerCertificate один оператор return true; чтобы убедиться, что проблема ТОЛЬКО в сертификате и остальной код работает. (Ну или там ещё десятки ошибок, но это уже ОТДЕЛЬНЫЙ ВОПРОС, потому что ошибка "удаленный сертификат недействителен" точно бы пропала).

    // The following method is invoked by the RemoteCertificateValidationDelegate.
    public static bool ValidateServerCertificate(
          object sender,
          X509Certificate certificate,
          X509Chain chain,
          SslPolicyErrors sslPolicyErrors)
    {
        return true;

        //if (sslPolicyErrors == SslPolicyErrors.None)
            //return true;

        //Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

        // Do not allow this client to communicate with unauthenticated servers.
        //return false;
    }

Самое главное, что мне хотелось бы упомянуть: о том, что если вы всё-таки уберёте проверку сертификата и всё заработает -- то нельзя до продакшена доводить код с убранной проверкой, потому что у вас никакого защищённого соединения не будет. Атакуй кто хочешь, подменяй сертификаты как хочешь.

2
  • В любом случае падает на сервере, а не на клиенте, сейчас использую другие купленные сертификаты. Изменил код в вопросе.
    – Алёна
    10 июн 2017 в 16:14
  • @Oma Ваши беды идут в основном не от плохого кода, а от того, что вы не умеете правильно изготавливать и устанавливать сертификаты. Этих подробностей в вопросе у вас нет, а они очень существенны. Тут ещё пара подсказок, почитайте.
    – A K
    11 июн 2017 в 9:20

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.