简体   繁体   English

SSL客户端/服务器相互认证

[英]SSL client/server mutual authentication

Hello I am trying to do in C# an ssl client/server communication with mutual authentication using server and client certificate.您好,我正在尝试在 C# 中进行 ssl 客户端/服务器通信,并使用服务器和客户端证书进行相互身份验证。 A managed to do the ssl communication only using server certificate, where on the client side I use sth like that: A 设法仅使用服务器证书进行 ssl 通信,在客户端我使用这样的东西:

TcpClient client = new TcpClient(machineName, port);
//Create an SSL stream that will close the client's stream.
   SslStream sslStream = new SslStream(
   client.GetStream(),
   false,
   new RemoteCertificateValidationCallback(ValidateServerCertificate),
   null
   );
try
{
    // The server name must match the name on the server certificate.
    sslStream.AuthenticateAsClient(serverName);
}
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;
} 

I assume I would need to use我想我需要使用

AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)

method, am I corrent?方法,我对吗? Could anyone please show me how to use it with all things around?Even on the server side, or point me to a basic example?谁能告诉我如何将它与周围的所有东西一起使用?即使在服务器端,或者指向一个基本示例?

Thank you a lot.十分感谢。

static void HTTPSClient()
{
    try
    {
        string message = "GET / HTTP/1.0\r\nHost: host.com\r\n\r\n";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

        string server = "host.com";
        int nPort = 443;
        TcpClient client = new TcpClient(server, nPort);

        X509Certificate2Collection cCollection = new X509Certificate2Collection();
        cCollection.Add(new X509Certificate2("cert.pfx", "password"));


        using (SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
        {
            // Add a client certificate to the ssl connection
            sslStream.AuthenticateAsClient(server, cCollection, System.Security.Authentication.SslProtocols.Default, true);

            sslStream.Write(data, 0, data.Length);

            data = new Byte[8192];
            int bytes = 0;
            string responseData = "";

            do
            {
                bytes = sslStream.Read(data, 0, data.Length);
                if (bytes > 0)
                {
                    responseData += System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                }
            }
            while (bytes > 0);

            Console.WriteLine("Response: " + responseData);
        }

        // Disconnect and close the client
        client.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.ToString());
    }
}

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;
}
  1. You need a x509 self certificate, to create it simple, download pluralsight self cert您需要一个 x509 自我证书,要简单地创建它,请下载复数视力自我证书
  2. Generate certificate as in image如图所示生成证书
  3. Create new web site, there choose wcf service.创建新的 web 站点,选择 wcf 服务。
  4. Add in solution new console application, to test our service.添加解决方案新的控制台应用程序,以测试我们的服务。
  5. In web.config of service put configuration:在 web.config 的 service put 配置中:

     <?xml version="1.0"?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="ServiceCredentialsBehavior"> <serviceCredentials> <serviceCertificate findValue="cn=cool" storeName="TrustedPeople" storeLocation="CurrentUser" /> </serviceCredentials> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="ServiceCredentialsBehavior" name="Service"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="MessageAndUserName" name="SecuredByTransportEndpoint" contract="IService"/> </service> </services> <bindings> <wsHttpBinding> <binding name="MessageAndUserName"> <security mode="Message"> <message clientCredentialType="UserName"/> </security> </binding> </wsHttpBinding> </bindings> <client/>

  6. In Service class, delete existing methods and add:在服务 class 中,删除现有方法并添加:

    public string TestAccess() { return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;公共字符串 TestAccess() { return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name; } }

  7. in IService delete Data Contract, delete operation contracts and add new operation contract:在 IService 中删除数据合约,删除操作合约并添加新的操作合约:

    [OperationContract] [运营合同]
    public string TestAccess();公共字符串 TestAccess();

  8. Run service and add service reference in client application to our service运行服务并将客户端应用程序中的服务引用添加到我们的服务

  9. Client config:客户端配置:

     <?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="LocalCertValidation"> <clientCredentials> <serviceCertificate> <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="CurrentUser" /> </serviceCertificate> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IService" > <security mode="Message"> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="your service addresss" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference1.IService" name="WSHttpBinding_IService" behaviorConfiguration="LocalCertValidation"> <identity> <dns value ="cool" /> </identity> </endpoint> </client>

  10. Client code:客户端代码:

    ServiceClient client = new ServiceClient();服务客户端客户端 = 新服务客户端();
    client.ClientCredentials.UserName.UserName = "Your windows user"; client.ClientCredentials.UserName.UserName = "您的 windows 用户";
    client.ClientCredentials.UserName.Password = "Your windows user password"; client.ClientCredentials.UserName.Password = "您的 windows 用户密码";
    Console.WriteLine(client.TestAccess()); Console.WriteLine(client.TestAccess());
    Console.ReadLine(); Console.ReadLine();

  11. if you dont want to use windows login/password you have to create a custom user/passwd validator ->msdn :如果您不想使用 windows 登录名/密码,则必须创建自定义用户/密码验证器->msdn
    Regards,问候,

    Sergiu.塞尔吉乌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET Mutual SSL握手&#39;客户端身份验证&#39; - .NET Mutual SSL handshake 'Client Authentication' SSL客户端证书/与ServiceStack的相互身份验证(HttpListener) - SSL client certificates / mutual authentication with ServiceStack (HttpListener) SSL/TLS 中的相互身份验证 - Mutual authentication in SSL/TLS SSL相互认证错误和问题 - SSL mutual authentication error and questions 相互SSL身份验证 - sslstream中的本地证书在客户端上返回“null”而不是证书 - Mutual SSL Authentication - Local certificate in sslstream returning 'null' instead of certificate on client 带SSL的C#异步Tcp服务器。 如何与iOS NSStream进行相互身份验证? - C# Asynchronous Tcp Server with SSL. How can I get mutual authentication with iOS NSStream? 具有相互身份验证的服务客户端(双向客户端证书身份验证) - Service client with Mutual Authentication (2-way client certificate authentication) WCF和SSL相互身份验证403-禁止:访问被拒绝 - WCF and SSL Mutual Authentication 403 - Forbidden: Access is denied 客户端服务器验证 - Client Server Authentication 在MMC控制台中用于相互(对等)身份验证的SSL证书的安装位置 - Where to install SSL Certificate in MMC console for mutual (peer-peer) authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM