C#中使用SslStream类来创建SSL服务器.docx
《C#中使用SslStream类来创建SSL服务器.docx》由会员分享,可在线阅读,更多相关《C#中使用SslStream类来创建SSL服务器.docx(8页珍藏版)》请在冰豆网上搜索。
C#中使用SslStream类来创建SSL服务器
C#中使用SslStream类来创建SSL服务器
//VisualC#
usingSystem;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Net.Security;
usingSystem.Text;
usingSystem.Security.Authentication;
usingSystem.Security.Cryptography.X509Certificates;
namespaceExamples.System.Net
{
publicsealedclassSslTcpServer
{
staticX509CertificateserverCertificate=null;
publicstaticvoidRunServer(stringcertificate)
{
serverCertificate=X509Certificate.CreateFromCertFile(certificate);
TcpListenerlistener=newTcpListener(IPAddress.Any,8080);
listener.Start();
while(true)
{
Console.WriteLine("Waitingforaclienttoconnect...");
TcpClientclient=listener.AcceptTcpClient();
ProcessClient(client);
}
}
staticvoidProcessClient(TcpClientclient)
{
SslStreamsslStream=newSslStream
(client.GetStream(),false);
try
{
sslStream.AuthenticateAsServer(serverCertificate,
false,SslProtocols.Tls,true);
DisplaySecurityLevel(sslStream);
DisplaySecurityServices(sslStream);
DisplayCertificateInformation(sslStream);
DisplayStreamProperties(sslStream);
sslStream.ReadTimeout=5000;
sslStream.WriteTimeout=5000;
Console.WriteLine("Waitingforclientmessage...");
stringmessageData=ReadMessage(sslStream);
Console.WriteLine("Received:
{0}",messageData);
byte[]message=Encoding.UTF8.GetBytes("Hellofromtheserver.");
Console.WriteLine("Sendinghellomessage.");
sslStream.Write(message);
}
catch(AuthenticationExceptione)
{
Console.WriteLine("Exception:
{0}",e.Message);
if(e.InnerException!
=null)
{
Console.WriteLine("Innerexception:
{0}",e.InnerException.Message);
}
Console.WriteLine("Authenticationfailed-closingtheconnection.");
sslStream.Close();
client.Close();
return;
}
finally
{
sslStream.Close();
client.Close();
}
}
staticstringReadMessage(SslStreamsslStream)
{
byte[]buffer=newbyte[2048];
StringBuildermessageData=newStringBuilder();
intbytes=-1;
do
{
bytes=sslStream.Read(buffer,0,buffer.Length);
Decoderdecoder=Encoding.UTF8.GetDecoder();
char[]chars=newchar[decoder.GetCharCount(buffer,0,bytes)];
decoder.GetChars(buffer,0,bytes,chars,0);
messageData.Append(chars);
if(messageData.ToString().IndexOf("")!
=-1)
{
break;
}
}
while(bytes!
=0);
returnmessageData.ToString();
}
staticvoidDisplaySecurityLevel(SslStreamstream)
{
Console.WriteLine("Cipher:
{0}strength{1}",stream.CipherAlgorithm,stream.CipherStrength);
Console.WriteLine("Hash:
{0}strength{1}",stream.HashAlgorithm,stream.HashStrength);
Console.WriteLine("Keyexchange:
{0}strength{1}",stream.KeyExchangeAlgorithm,stream.KeyExchangeStrength);
Console.WriteLine("Protocol:
{0}",stream.SslProtocol);
}
staticvoidDisplaySecurityServices(SslStreamstream)
{
Console.WriteLine("Isauthenticated:
{0}asserver?
{1}",stream.IsAuthenticated,stream.IsServer);
Console.WriteLine("IsSigned:
{0}",stream.IsSigned);
Console.WriteLine("IsEncrypted:
{0}",stream.IsEncrypted);
}
staticvoidDisplayStreamProperties(SslStreamstream)
{
Console.WriteLine("Canread:
{0},write{1}",stream.CanRead,stream.CanWrite);
Console.WriteLine("Cantimeout:
{0}",stream.CanTimeout);
}
staticvoidDisplayCertificateInformation(SslStreamstream)
{
Console.WriteLine("Certificaterevocationlistchecked:
{0}",stream.CheckCertRevocationStatus);
X509CertificatelocalCertificate=stream.LocalCertificate;
if(stream.LocalCertificate!
=null)
{
Console.WriteLine("Localcertwasissuedto{0}andisvalidfrom{1}until{2}.",
localCertificate.Subject,
localCertificate.GetEffectiveDateString(),
localCertificate.GetExpirationDateString());
}
else
{
Console.WriteLine("Localcertificateisnull.");
}
X509CertificateremoteCertificate=stream.RemoteCertificate;
if(stream.RemoteCertificate!
=null)
{
Console.WriteLine("Remotecertwasissuedto{0}andisvalidfrom{1}until{2}.",
remoteCertificate.Subject,
remoteCertificate.GetEffectiveDateString(),
remoteCertificate.GetExpirationDateString());
}
else
{
Console.WriteLine("Remotecertificateisnull.");
}
}
privatestaticvoidDisplayUsage()
{
Console.WriteLine("Tostarttheserverspecify:
");
Console.WriteLine("serverSynccertificateFile.cer");
Environment.Exit
(1);
}
publicstaticintMain(string[]args)
{
stringcertificate=null;
if(args==null||args.Length<1)
{
DisplayUsage();
}
certificate=args[0];
SslTcpServer.RunServer(certificate);
return0;
}
}
}
C#中使用SslStream类来创建SSL客户端
//VisualC#
usingSystem;
usingSystem.Collections;
usingSystem.Net;
usingSystem.Net.Security;
usingSystem.Net.Sockets;
usingSystem.Security.Authentication;
usingSystem.Text;
usingSystem.Security.Cryptography.X509Certificates;
namespaceExamples.System.Net
{
publicclassSslTcpClient
{
privatestaticHashtablecertificateErrors=newHashtable();
publicstaticboolValidateServerCertificate(
objectsender,
X509Certificatecertificate,
X509Chainchain,
SslPolicyErrorssslPolicyErrors)
{
if(sslPolicyErrors==SslPolicyErrors.None)
returntrue;
Console.WriteLine("Certificateerror:
{0}",sslPolicyErrors);
returnfalse;
}
publicstaticvoidRunClient(stringmachineName,stringserverName)
{
TcpClientclient=newTcpClient(machineName,443);
Console.WriteLine("Clientconnected.");
SslStreamsslStream=newSslStream(
client.GetStream(),
false,
newRemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
try
{
sslStream.AuthenticateAsClient(serverName);
}
catch(AuthenticationExceptione)
{
Console.WriteLine("Exception:
{0}",e.Message);
if(e.InnerException!
=null)
{
Console.WriteLine("Innerexception:
{0}",e.InnerException.Message);
}
Console.WriteLine("Authenticationfailed-closingtheconnection.");
client.Close();
return;
}
byte[]messsage=Encoding.UTF8.GetBytes("Hellofromtheclient.");
sslStream.Write(messsage);
sslStream.Flush();
stringserverMessage=ReadMessage(sslStream);
Console.WriteLine("Serversays:
{0}",serverMessage);
client.Close();
Console.WriteLine("Clientclosed.");
}
staticstringReadMessage(SslStreamsslStream)
{
byte[]buffer=newbyte[2048];
StringBuildermessageData=newStringBuilder();
intbytes=-1;
do
{
bytes=sslStream.Read(buffer,0,buffer.Length);
Decoderdecoder=Encoding.UTF8.GetDecoder();
char[]chars=newchar[decoder.GetCharCount(buffer,0,bytes)];
decoder.GetChars(buffer,0,bytes,chars,0);
messageData.Append(chars);
if(messageData.ToString().IndexOf("")!
=-1)
{
break;
}
}
while(bytes!
=0);
returnmessageData.ToString();
}
privatestaticvoidDisplayUsage()
{
Console.WriteLine("Tostarttheclientspecify:
");
Console.WriteLine("clientSyncmachineName[serverName]");
Environment.Exit
(1);
}
publicstaticintMain(string[]args)
{
stringserverCertificateName=null;
stringmachineName=null;
if(args==null||args.Length<1)
{
DisplayUsage();
}
machineName=args[0];
if(args.Length<2)
{
serverCertificateName=machineName;
}
else
{
serverCertificat