X.509 給出的鑑別框架是一種基於公開密鑰體制的鑑別業務密鑰管理。一個用戶有兩把密鑰:一把是用戶的專用密鑰(簡稱爲:私鑰),另外一把是其餘用戶均可獲得和利用的公共密鑰(簡稱爲:公鑰)。該鑑別框架容許用戶將其公開密鑰存放在CA的目錄項中。一個用戶若是想與另外一個用戶交換祕密信息,就能夠直接從對方的目錄項中得到相應的公開密鑰,用於各類安全服務。html
Windows環境下,有三種方法:經過CA獲取證書;經過微軟提供的makecert 工具獲得測試證書;編程的方法建立,.Net提供了X509Certificate2 類,該類能夠用於建立證書,但只能從RawData中建立,建立後沒法修改除FriendlyName之外的任何屬性。編程
本文介紹第二種方法:安全
1)先進入到vs20**的命令行狀態,即:開始-->程序-->Microsoft Visual Studio 20**-->Visual Studio Tools-->Visual Studio 20** 命令提示服務器
2)鍵入:makecert -r -pe -n "CN=MyServer" -ss My -sky exchangeapp
上面一行的意思就是製做一個CN=MyServer的服務器證書,默認存儲在CurrentUser"My這個位置,同時這個證書標識爲可導出。框架
(詳細的MakeCert參數可參見http://msdn.microsoft.com/zh-cn/bfsktky3(vs.80).aspx)socket
3)再輸入:makecert -r -pe -n "CN=MyClient" -ss My -sky exchange 生成客戶端證書
工具
4)查看:能夠在IE裏查看到,IE-->工具-->Internet選項-->內容-->證書測試
5)開始-->運行-->MMC : 添加/刪除管理單元ui
6)添加「證書」 ,「個人用戶帳戶」
7)將「我的」下的對應證書複製到「受信任的根證書頒發機構」下證書目錄,證書就可使用了
本文參考:http://www.cnblogs.com/whtydn/archive/2009/12/23/1630750.html
http://blog.csdn.net/wyxhd2008/article/details/7962539
下面是whtydn的代碼(http://www.cnblogs.com/whtydn/archive/2009/12/23/1630750.html)
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"), 901);
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 = 5000;
sslStream.WriteTimeout = 5000;
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[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("") != -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.");
}
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 == 0) return;
serverCertificate = certs[0];
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();
}
}
}
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, 901);
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[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
bytes = sslStream.Read(buffer, 0, 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, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 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 void Main(string[] args)
{
string machineName = null;
machineName = "192.168.20.139";
try
{
RunClient(machineName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
}
ValidateServerCertificate 是向服務器驗證證書的方法,若是上面返回的SslPolicyErrors枚舉值不是None你就應該檢查你的證書是否正確, 是否添加到信任裏面。
其它參考文章:http://www.cnblogs.com/chnking/archive/2007/08/18/860983.html
http://www.cnblogs.com/sleepingwit/archive/2008/10/30/1323334.html