您的位置:首页 > 编程语言 > C#

c#编写ssl socket 安全的套接字层传输

2009-12-08 20:55 471 查看
c#编写ssl socket 安全的套接字层传输

ssihc0@163.com QQ:47400789

这里使用了Chilkat组件,,

记得调试这个程序的时候添加引用   ChilkatDotNet2.dll 文件



SSL Client Certificate
Demonstrates how to connect to an SSL server using a client-side certificate, send a simple message, receive a simple response, and disconnect.

Download Chilkat .NET for 2.0 / 3.5 Framework

Download Chilkat .NET for 64-bit 2.0 / 3.5 Framework (x64)

Download Chilkat .NET for 1.0 / 1.1 Framework

Chilkat.Socket socket = new Chilkat.Socket();

bool success;
success = socket.UnlockComponent("Anything for 30-day trial");
if (success != true) {
MessageBox.Show("Failed to unlock component");
return;
}

//  Create an instance of a certificate store object, load a PFX file,
//  locate the certificate we need, and use it for signing.
//  (a PFX file may contain more than one certificate.)
Chilkat.CertStore certStore = new Chilkat.CertStore();
//  The 1st argument is the filename, the 2nd arg is the
//  PFX file's password:
success = certStore.LoadPfxFile("chilkat_secret.pfx","secret");
if (success != true) {
MessageBox.Show(certStore.LastErrorText);
return;
}

Chilkat.Cert cert = null;
cert = certStore.FindCertBySubjectCN("Chilkat Software, Inc.");
if (cert == null ) {
MessageBox.Show(certStore.LastErrorText);
return;
}

socket.SetSslClientCert(cert);

bool ssl;
ssl = true;
int maxWaitMillisec;
maxWaitMillisec = 20000;

//  The SSL server hostname may be an IP address, a domain name,
//  or "localhost".  You'll need to change this:
string sslServerHost;
sslServerHost = "123.123.88.88";
int sslServerPort;
sslServerPort = 8123;

//  Connect to the SSL server:
success = socket.Connect(sslServerHost,sslServerPort,ssl,maxWaitMillisec);
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}

//  Set maximum timeouts for reading an writing (in millisec)
socket.MaxReadIdleMs = 20000;
socket.MaxSendIdleMs = 20000;

//  Send a "Hello Server! -EOM-" message:
success = socket.SendString("Hello Server! -EOM-");
if (success != true) {
MessageBox.Show(socket.LastErrorText);
return;
}

//  The server (in this example) is going to send a "Hello Client! -EOM-"
//  message.  Read it:
string receivedMsg;
receivedMsg = socket.ReceiveUntilMatch("-EOM-");
if (receivedMsg == null ) {
MessageBox.Show(socket.LastErrorText);
return;
}

//  Close the connection with the server
//  Wait a max of 20 seconds (20000 millsec)
socket.Close(20000);

MessageBox.Show(receivedMsg);


这里是参考地址

http://www.example-code.com/csharp/ssl_client_certificate.asp

http://www.chilkatsoft.com/refdoc/

在上面代码中,,除了,,证书和密码为,,,

certStore.FindCertBySubjectCN("Chilkat Software, Inc.");

FindCertBySubjectCN 这个方法里的参数  为证书里的 SubjectCN 值

查看SubjectCN的代码如下

using System;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace 读取证书
{
class Program
{
//Reads a file.
internal static byte[] ReadFile (string fileName)
{
FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
int size = (int)f.Length;
byte[] data = new byte[size];
size = f.Read(data, 0, size);
f.Close();
return data;
}
//Main method begins here.
static void Main(string[] args)
{
//Test for correct number of arguments.
//if (args.Length < 1)
//{
//    Console.WriteLine("Usage: CertInfo <filename>");
//    return;
//}
try
{
X509Certificate2 x509 = new X509Certificate2();
//Create X509Certificate2 object from .cer file.
// byte[] rawData = ReadFile(args[0]);
byte[] rawData = ReadFile(@"证书 ");

x509.Import(rawData, "密码", X509KeyStorageFlags.DefaultKeySet);

//Print to console information contained in the certificate.
Console.WriteLine("{0}Subject: {1}{0}", Environment.NewLine,x509.Subject);
Console.WriteLine("{0}Issuer: {1}{0}", Environment.NewLine,x509.Issuer);
Console.WriteLine("{0}Version: {1}{0}", Environment.NewLine,x509.Version);
Console.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine,x509.NotBefore);
Console.WriteLine("{0}Expiry Date: {1}{0}", Environment.NewLine,x509.NotAfter);
Console.WriteLine("{0}Thumbprint: {1}{0}", Environment.NewLine,x509.Thumbprint);
Console.WriteLine("{0}Serial Number: {1}{0}", Environment.NewLine,x509.SerialNumber);
Console.WriteLine("{0}Friendly Name: {1}{0}", Environment.NewLine,x509.PublicKey.Oid.FriendlyName);
Console.WriteLine("{0}Public Key Format: {1}{0}",Environment.NewLine,x509.PublicKey.EncodedKeyValue.Format(true));
Console.WriteLine("{0}Raw Data Length: {1}{0}", Environment.NewLine,x509.RawData.Length);
Console.WriteLine("{0}Certificate to string: {1}{0}", Environment.NewLine,x509.ToString(true));
Console.WriteLine("{0}Certificate to XML String: {1}{0}",Environment.NewLine,x509.PublicKey.Key.ToXmlString(false));

//Add the certificate to a X509Store.
X509Store store = new X509Store();
store.Open(OpenFlags.MaxAllowed);
store.Add(x509);
store.Close();
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Error: The directory specified could not be found.");
}
catch (IOException)
{
Console.WriteLine("Error: A file in the directory could not be accessed.");
}
catch (NullReferenceException)
{
Console.WriteLine("File must be a .cer file. Program does not have access to that type of file.");
}
Console.ReadKey();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: