AuthenticateAsServer() 处理证书时发生未知错误

问题描述

我正在努力使用 .NET Core 5.0 中的 AuthenticateAsServer() 函数对服务器进行身份验证。我有一个 HTTPS 安全网站,带有由 CA 签名的证书,我获得了私钥,私钥链接到我运行 .NET 应用程序的服务器上的证书(如果不是托管网站的同一台机器)事项)。 我尝试这样做的原因是让 WebSockets 再次工作(目前我只能让它们在 HTTP 上工作)。我得到的内部异常是:

处理证书时发生未知错误

我在客户端加载页面时得到它(WebSocket 客户端尝试在加载后自动连接)。这是我加载证书的方式:

public static X509Certificate2 getCertBySNumber(string SerialNumber)
    {
        X509Certificate2 Certificate = new X509Certificate2();
        try
        {
            X509Store store = new X509Store(StoreName.My,StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            try
            {
                X509Certificate2Collection Results = store.Certificates.Find(X509FindType.FindBySerialNumber,SerialNumber,false);
                foreach (X509Certificate2 cert in Results)
                {
                    Console.WriteLine(cert.GetExpirationDateString());
                }
                if (Results.Count == 0)
                {
                    throw new Exception("Unable to find certificate!");
                }
                else
                {
                    Certificate = Results[0];
                    Console.WriteLine("found a certificate " + Certificate.SerialNumber + " private key: " + Certificate.HasPrivateKey + " verified: " + Certificate.Verify()); //OUTPUT: found a certificate XXXX3FAF3A57F7D69XXXX34D3CD82B private key: True verified: True
                                            
                }
            }
            finally
            {
                store.Close(); 
            }
            return Certificate;
        }
        catch (Exception e)
        {
            Console.WriteLine("EXCEPTION: {0}",e.Message);
            return null;
        }
    }

这就是我接受传入连接并尝试对服务器进行身份验证的方式

 TcpListener listener = new TcpListener(port);
        listener.Start();
        X509Certificate2 Certificate = getCertBySNumber("XXXX3FAF3A57F7D69XXXX34D3CD82B");
         try
        {

        while (true)
        {   
            Console.WriteLine("Waiting for a connection...");
            TcpClient client= listener.AcceptTcpClient();
            SslStream sslStream = new SslStream(client.GetStream(),false);
            try
            {
                sslStream.AuthenticateAsServer(Certificate,false,SslProtocols.Tls12,false);//<-- error here
                Console.WriteLine("success");
            }
        }
        }

有没有人遇到过这个问题?我试图更深入地研究异常,但没有得到有用的信息。任何帮助表示赞赏!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)