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

标签 c# authentication ssl client

您好,我正在尝试在 C# 中使用服务器和客户端证书通过相互身份验证进行 ssl 客户端/服务器通信。设法仅使用服务器证书进行 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;
} 

我假设我需要使用

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

方法,我是正确的吗?谁能告诉我如何在周围的所有事物中使用它?甚至在服务器端,或者给我一个基本的例子?

非常感谢。

最佳答案

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

关于c# - SSL 客户端/服务器相互认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527429/

相关文章:

c# - Entity Framework 外键问题

c# - 如何读取文本文件并循环遍历重复部分?

authentication - 限制特定仪表板中的某些 kibana 用户

从 https 切换到 http 时 session 丢失 (tomcat 6.0.26)

python - SSL.SSLError : tlsv1 alert protocol version

c# - 查找鼠标指针所在的监视器/屏幕

c# - 如何使用 Mono 查看 .Net/C# 中的 Unicode 规范化算法?

php - 使用 salt login 的 Symfony 2 总是返回 Bad credentials

powershell - 是否可以编写 Azure 应用服务身份验证配置脚本?

ssl - 使用 maven 运行 Selenium RC - https 站点有证书问题