问题描述
我正在尝试在服务器和客户端之间建立TCP / IP连接,并且为了确保安全连接,应该启用TLS 1.2。该证书是使用开放SSL创建的,某些消息人士称,这是创建用于测试目的的自签名证书的最佳方法。以下是我使用的MSDN代码。我已将证书放在服务器存储中以供使用。当我尝试从服务器端进行侦听时,我可以从客户端进行连接,并且正在传输数据。但是我觉得我在这里错过了很多事情。
我是套接字连接实现的新手。最初,我有很多问题。在网上冲浪可以解决一些问题,但我却找不到其中的一些答案。以下是我的疑问。
- 此处的私钥和公钥是什么?我没有在任何地方使用它。但是它似乎以某种方式起作用。请让我知道如何将其添加到以下代码中?
- 我可以看到服务器正在将带有证书信息的消息带给正在通过AuthenticateAsClient方法验证的客户端。这足以检查服务器的真实性吗?
- 如何使用AuthenticateAsServer验证客户端?我们需要在客户端创建一个新的证书还是可以使用相同的旧证书?
- 如何验证我的实施是否正常?如何确保通话安全?
- 什么是数字证书?它与普通证书有何不同?何时使用?
服务器端代码:
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.IO;
namespace Examples.System.Net
{
public sealed class SslTcpserver
{
static X509Certificate serverCertificate = null;
// The certificate parameter specifies the name of the file
// containing the machine certificate.
public static void RunServer(string certificate)
{
serverCertificate = "getting the certificate from the store"
// Create a TCP/IP (IPv4) socket and listen for incoming connections.
TcpListener listener = new TcpListener(IPAddress.Any,8080);
listener.Start();
while (true)
{
Console.WriteLine("Waiting for a client to connect...");
// Application blocks while waiting for an incoming connection.
// Type CNTL-C to terminate the server.
TcpClient client = listener.AcceptTcpClient();
ProcessClient(client);
}
}
static void ProcessClient (TcpClient client)
{
// A client has connected. Create the
// SslStream using the client's network stream.
SslStream sslStream = new SslStream(
client.GetStream(),false);
// Authenticate the server but don't require the client to authenticate.
try
{
sslStream.AuthenticateAsServer(serverCertificate,clientCertificaterequired: false,SslProtocols.Tls12,checkCertificateRevocation: true);
// display the properties and settings for the authenticated stream.
displaySecurityLevel(sslStream);
displaySecurityServices(sslStream);
displayCertificateinformation(sslStream);
displayStreamProperties(sslStream);
// Set timeouts for the read and write to 5 seconds.
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
// Read a message from the client.
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
{
// The client stream will be closed with the sslStream
// because we specified this behavior when creating
// the sslStream.
sslStream.Close();
client.Close();
}
}
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the client.
// The client signals the end of the message using the
// "<EOF>" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
// Read the client's test message.
bytes = sslStream.Read(buffer,buffer.Length);
// Use Decoder class to convert from bytes to UTF8
// in case a character spans two buffers.
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer,bytes)];
decoder.GetChars(buffer,bytes,chars,0);
messageData.Append (chars);
// Check for EOF or an empty message.
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes !=0);
return messageData.ToString();
}
static void displaySecurityLevel(SslStream stream)
{
Console.WriteLine("Cipher: {0} strength {1}",stream.CipherAlgorithm,stream.CipherStrength);
Console.WriteLine("Hash: {0} strength {1}",stream.HashAlgorithm,stream.HashStrength);
Console.WriteLine("Key exchange: {0} strength {1}",stream.KeyExchangeAlgorithm,stream.KeyExchangeStrength);
Console.WriteLine("Protocol: {0}",stream.SslProtocol);
}
static void displaySecurityServices(SslStream stream)
{
Console.WriteLine("Is authenticated: {0} as server? {1}",stream.IsAuthenticated,stream.IsServer);
Console.WriteLine("IsSigned: {0}",stream.IsSigned);
Console.WriteLine("Is Encrypted: {0}",stream.IsEncrypted);
}
static void displayStreamProperties(SslStream stream)
{
Console.WriteLine("Can read: {0},write {1}",stream.CanRead,stream.CanWrite);
Console.WriteLine("Can timeout: {0}",stream.CanTimeout);
}
static void displayCertificateinformation(SslStream stream)
{
Console.WriteLine("Certificate revocation list checked: {0}",stream.CheckCertRevocationStatus);
X509Certificate localCertificate = stream.LocalCertificate;
if (stream.LocalCertificate != null)
{
Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",localCertificate.Subject,localCertificate.GetEffectiveDateString(),localCertificate.GetExpirationDateString());
} else
{
Console.WriteLine("Local certificate is null.");
}
// display the properties of the client's certificate.
X509Certificate remoteCertificate = stream.RemoteCertificate;
if (stream.RemoteCertificate != null)
{
Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",remoteCertificate.Subject,remoteCertificate.GetEffectiveDateString(),remoteCertificate.GetExpirationDateString());
} else
{
Console.WriteLine("Remote certificate is null.");
}
}
private static void displayUsage()
{
Console.WriteLine("To start the server specify:");
Console.WriteLine("serverSync certificateFile.cer");
Environment.Exit(1);
}
public static int Main(string[] args)
{
string certificate = null;
if (args == null ||args.Length < 1 )
{
displayUsage();
}
certificate = args[0];
SslTcpserver.RunServer (certificate);
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();
// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(
object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}",sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
public static void runclient(string machineName,string serverName)
{
// Create a TCP/IP client socket.
// machineName is the host running the server application.
TcpClient client = new TcpClient(machineName,8080);
Console.WriteLine("Client connected.");
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
client.GetStream(),false,new RemoteCertificateValidationCallback (ValidateServerCertificate),null
);
// The server name must match the name on the server certificate.
try
{
sslStream.AuthenticateAsClient(serverName,null,true);
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}",e.InnerException.Message);
}
Console.WriteLine ("Authentication Failed - closing the connection.");
client.Close();
return;
}
// Encode a test message into a byte array.
// Signal the end of the message using the "<EOF>".
byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
// Send hello message to the server.
sslStream.Write(messsage);
sslStream.Flush();
// Read message from the server.
string serverMessage = ReadMessage(sslStream);
Console.WriteLine("Server says: {0}",serverMessage);
// Close the client connection.
client.Close();
Console.WriteLine("Client closed.");
}
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the server.
// The end of the message is signaled using the
// "<EOF>" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sslStream.Read(buffer,bytes)];
decoder.GetChars(buffer,0);
messageData.Append (chars);
// Check for EOF.
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)
{
string serverCertificateName = null;
string machineName = null;
if (args == null ||args.Length <1 )
{
displayUsage();
}
// User can specify the machine name and server name.
// Server name must match the name on the server's certificate.
machineName = args[0];
if (args.Length <2 )
{
serverCertificateName = machineName;
}
else
{
serverCertificateName = args[1];
}
SslTcpClient.runclient (machineName,serverCertificateName);
return 0;
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)