Никак не получается соединить даже 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. Если есть у кого базовый рабочий пример, прошу поделиться.