为什么我每次都遇到RemoteCertificateNameMismatch?

Eri*_*ric 4 c# ssl x509certificate

考虑以下完整程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace RemoteCertNameMismatchDiagnosis
{
class Program
{
    private static bool AcceptAllCertificates(object sender, X509Certificate certificate,
                                                                                        X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine(sslPolicyErrors.ToString());
        return true;
    }

    static void Main(string[] args)
    {
        TcpClient client;
        SslStream sslStream;

        bool acceptAnyCert = false;

        client = new TcpClient("google.com", 443);
        if (acceptAnyCert)
            sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptAllCertificates), null);
        else
            sslStream = new SslStream(client.GetStream(), false);

        try
        {
            sslStream.AuthenticateAsClient("test client");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.ReadLine();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

它报告了这个例外

System.Security.Authentication.AuthenticationException:根据验证过程,远程证书无效.

每次.通过acceptAnyCert在第26行更改为true,我可以输出它

RemoteCertificateNameMismatch

,让我相信它对证书上的名字不满意.

无论我指向google.com,amazon.com还是第28行的其他任何地方,此行为仍然存在.我不认为google,microsoft和amazon都有缺陷证书.我究竟做错了什么?

cyn*_*nic 10

您需要传递"google.com"AuthenticateAsClient它 - 它希望服务器名称作为参数,而不是您的客户端名称.