一、x.509证书

1.制作证书

先进入到vs2005的命令行状态,即:
开始-->程序-->Microsoft Visual Studio 2005-->Visual Studio Tools-->Visual Studio 2005 命令提示

键入:

makecert -r -pe -n "CN=MyServer" -ss My -sky exchange

解释一下:makecert.exe是一个专门用来制作证书的小工具,上面一行的意思就是制作一个CN=MyServer的服务器证书,默认存储在CurrentUser"My这个位置,同时这个证书标识为可导出。(详细的

MakeCert参数可参见http://msdn.microsoft.com/zh-cn/bfsktky3(vs.80).aspx)

再输入:

makecert -r -pe -n "CN=MyClient" -ss My -sky exchange

生成客户端证书,证书生成好以后,可以在IE里查看到,IE-->工具-->Internet选项-->内容-->证书

记得要把证书导入到受信任的那栏,不然是访问不到的, 然后在IE-->工具-->Internet选项-->内容-->证书里导出一个CER,面通知过程中选不要是私钥, 这样给客户端使用

socket服务器的建立代码如下,注意所引用的命名空间:

using System;
using System.ServiceModel;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors; namespace ConsoleApp
{
public class Program
{
static X509Certificate serverCertificate = null; public static void RunServer()
{
//serverCertificate = X509Certificate.CreateFromSignedFile(@"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\samool.pvk");
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.20.139"), );
listener.Start();
while (true)
{
try
{
Console.WriteLine("Waiting for a client to connect...");
TcpClient client = listener.AcceptTcpClient();
ProcessClient(client);
}
catch
{ }
}
} static void ProcessClient(TcpClient client)
{
SslStream sslStream = new SslStream(client.GetStream(), false);
try
{
sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);
DisplaySecurityLevel(sslStream);
DisplaySecurityServices(sslStream);
DisplayCertificateInformation(sslStream);
DisplayStreamProperties(sslStream); sslStream.ReadTimeout = ;
sslStream.WriteTimeout = ;
Console.WriteLine("Waiting for client message...");
string messageData = ReadMessage(sslStream);
Console.WriteLine("Received: {0}", messageData);
byte[] message = Encoding.UTF8.GetBytes("Hello from the server.");
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[];
StringBuilder messageData = new StringBuilder();
int bytes = -;
do
{
bytes = sslStream.Read(buffer, , buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, , bytes)];
decoder.GetChars(buffer, , bytes, chars, );
messageData.Append(chars);
if (messageData.ToString().IndexOf("") != -)
{
break;
}
}
while (bytes != ); 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.");
}
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 void Main(string[] args)
{
//string certificate = null;
//if (args == null || args.Length < 1)
//{
// DisplayUsage();
//}
//certificate = args[0];
try
{
X509Store store = new X509Store(StoreName.My);
store.Open(OpenFlags.ReadWrite); // 检索证书
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyServer", false); // vaildOnly = true时搜索无结果。
if (certs.Count == ) return; serverCertificate = certs[];
RunServer();
store.Close(); // 关闭存储区。
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
//return 0; //try
//{
// Console.WriteLine("服务端输出:" + ServiceSecurityContext.Current.PrimaryIdentity.AuthenticationType);
// Console.WriteLine(ServiceSecurityContext.Current.PrimaryIdentity.Name);
// Console.WriteLine("服务端时间:" + DateTime.Now.ToString());
//}
//catch (Exception ex)
//{
// Console.WriteLine(ex.Message);
//}
//Console.ReadLine(); }
} }

Sokect客户端代码如下:

using System;
using System.Security;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates; namespace ConsoleAppClient
{
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)
{
// Create a TCP/IP client socket.
// machineName is the host running the server application.
TcpClient client = new TcpClient(machineName, );
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. //X509Store store = new X509Store(StoreName.My);
//store.Open(OpenFlags.ReadWrite); //// 检索证书
//X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "MyServer", false); // vaildOnly = true时搜索无结果。 X509CertificateCollection certs = new X509CertificateCollection();
X509Certificate cert = X509Certificate.CreateFromCertFile(@"D:\cashcer.cer");
certs.Add(cert);
try
{
sslStream.AuthenticateAsClient("MyServer", certs, SslProtocols.Tls, false);
}
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;
}
// 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[];
StringBuilder messageData = new StringBuilder();
int bytes = -;
do
{
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, );
messageData.Append(chars);
// Check for EOF.
if (messageData.ToString().IndexOf("<EOF>") != -)
{
break;
}
} while (bytes != ); return messageData.ToString();
} private static void DisplayUsage()
{
Console.WriteLine("To start the client specify:");
Console.WriteLine("clientSync machineName [serverName]");
Environment.Exit();
} public static void Main(string[] args)
{
string machineName = null;
machineName = "192.168.20.139"; try
{
RunClient(machineName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
} }

运行就可以了。

注意的是证书的取得, 客户端有个向服务器验证证书的方法:

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;
}

如果上面返回的SslPolicyErrors枚举值不是None你就应该检查你的证书是否正确, 是否添加到信任里面。

转自http://www.cnblogs.com/whtydn/archive/2009/12/23/1630750.html

C# Socket SSL通讯笔记的更多相关文章

  1. TCP UDP Socket 即时通讯 API 示例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  2. ZeroC Ice启用SSL通讯的配置

    Zeroc ICE ( Internet Communications Engine )中间件号称标准统一,开源,跨平台,跨语言,分布式,安全,服务透明,负载均衡,面向对象,性能优越,防火墙穿透,通讯 ...

  3. sendEmail报错:at /usr/share/perl5/vendor_perl/IO/Socket/SSL.pm

    sendEmail发送邮件是出现以下报错: *******************************************************************  Using the ...

  4. OpenSSL进行SSL通讯的一些问题

    这两个星期真是被OpenSSL给烦透了,几个很简单基本的问题(如果没人告诉你真的很难测出来)把我搞的..哎,有时候真是不知道自己该不该搞技术,发现自己头脑真是蠢得很... 直接上正题. 第一个问题: ...

  5. Socket网络通讯开发总结之:Java 与 C进行Socket通讯 + [备忘] Java和C之间的通讯

    Socket网络通讯开发总结之:Java 与 C进行Socket通讯 http://blog.sina.com.cn/s/blog_55934df80100i55l.html (2010-04-08 ...

  6. .net平台下socket异步通讯(代码实例)

    你应该知道的.net平台下socket异步通讯(代码实例) 1,首先添加两个windows窗体项目,一个作为服务端server,一个作为客户端Client 2,然后添加服务端代码,添加命名空间,界面上 ...

  7. 第五十三节,socket模块介绍,socket单线程通讯

    socket单线程通讯,只能单线程通讯,不能并发 socket是基于(TCP.UDP.IP)的通讯.也叫做套接字 通讯过程由服务端的socket处理信息发送,由客户端的socket处理信息接收. so ...

  8. [dotnet core]使用Peach简化Socket网络通讯协议开发

    Peach是基于DotNetty的Socket网络通讯帮助类库,可以帮助开发者简化使用DotNetty,关于DotNetty可参考我之前的这篇文章. Peach内置实现了一个基于文本协议的Comman ...

  9. CentOS 7 下sendEmail发邮件失败,提示invalid SSL_version specified at /usr/share/perl5/vendor_perl/IO/Socket/SSL.pm line 415.

    系统环境CentOS Linux release 7.2.1511 (Core) sendEmail发送邮件是出现以下报错:************************************** ...

随机推荐

  1. iOS分类

    ios中的分类其实就是把两个类用两个或多个文件写的,,在平时的开发中我们会发现有的时候我们想要一个类多个什么功能  但是已经定义好的类中没有,,我们又不想更改我们的程序  那么现在的这种情况下我就可以 ...

  2. Do Palapala (this)

    Description 伟大的中国人民有宝箱容量为S(0<=S<=20000),有m个物品(0<m<=30,每个物品有一个体积(正整数).任取若干个装入箱内,使箱子的剩余空间为 ...

  3. [转载] 高大上的 CSS 效果:Shape Blobbing

    这篇大部分是转载,来自<高大上的 CSS 效果:Shape Blobbing>和 <Shape Blobbing in CSS> 有部分是自己理解和整理,配合效果要做出 app ...

  4. HTML5之Viewport详解

    做移动Web开发也有一年多的时间了,虽然手机上浏览器对于PC上来说很友好了,但是手机各种设备的显示尺寸分辨率大小不一也要花大心思兼容它们. 关于HTML5中Viewport的文章Google,百度一搜 ...

  5. php 文件操作类

    class fileInit { /** * 创建空文件 * @param string $filename 需要创建的文件 * @return */ public function create_f ...

  6. Ubuntu14.04安装Mongodb

    官网获取到最新的tgz包: 请查看自己的cpu这里是32位的. $sudo wget htps://fastdl.mongodb.org/linux/mongodb-linux-i686-2.6.7. ...

  7. 2-4. BCD解密(10)

    BCD数是用一个字节来表达两位十进制的数,每四个比特表示一位.所以如果一个BCD数的十六进制是0x12,它表达的就是十进制的12.但是小明没学过BCD,把所有的BCD数都当作二进制数转换成十进制输出了 ...

  8. html5介绍 之亮点特性

    html5 兴起- 乔帮助在2010年发布的:关于对flash的思考,提到有了h5放弃 flash   1 富图形,富媒体      2 本地存储     cookie   3 LBS      基于 ...

  9. 实现拦截API的钩子(Hook)

    道理不多讲,简单说就是将系统API的跳转地址,替换为我们自己写的API的地址,所以要求我们自定义的API函数要和被拦截的API有相同的参数.在用完后,记得恢复. 因为要挂全局的钩子,所以Hook的部分 ...

  10. PHP5中__call、__get、__set、__clone、__sleep、__wakeup的用法

    __construct(),__destruct(),__call(),__callStatic(),__get(),__set(),__isset(),__unset(),__sleep(),__w ...