簡體   English   中英

AuthenticateAsServer - 根據驗證過程,遠程證書無效

[英]AuthenticateAsServer - The remote certificate is invalid according to the validation procedure

我正在嘗試使用以下代碼創建測試客戶端/服務器連接:

    static void Main(string[] args)
    {
        var listenerThread = new Thread(ListenerThreadEntry);
        listenerThread.Start();

        Thread.Sleep(TimeSpan.FromSeconds(1));

        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        socket.Connect("localhost", Port);

        var rawStream = new NetworkStream(socket);
        var stream = new SslStream(rawStream, false, VerifyServerCertificate);
        var certificate = new X509Certificate(CertsPath + @"test.cer");
        var certificates = new X509CertificateCollection(new[] { certificate });
        stream.AuthenticateAsClient("localhost", certificates, SslProtocols.Tls, false);

        Thread.Sleep(TimeSpan.FromSeconds(1));
    }

    private static bool VerifyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    static void ListenerThreadEntry()
    {
        var listener = new TcpListener(IPAddress.Any, Port);
        listener.Start();

        var client = listener.AcceptTcpClient();
        var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
        var sslStream = new SslStream(client.GetStream(), false);
        sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false);

        Thread.Sleep(TimeSpan.FromSeconds(10));
    }

並且在AuthenticateAsServer方法中獲取“遠程證書根據驗證過程無效”錯誤消息。 使用以下命令創建證書並將其保存到文件:

makecert.exe -r -pe -n "CN=localhost" -a sha1 -sky exchange -sv test.pvk test.cer
pvk2pfx -pvk test.pvk -spc test.cer -pfx test.pfx

我錯過了什么?

檢查這些步驟,似乎工作,

1)First save the certificate in a file
2)Run MMC
3)Open the Certificate Manager (certmgr.msc in C:\Windows\System32)
4)You will see it opens 'Certificates - Current User'
5)In the menu, choose File, Add/Remove Snap-In
6)Now press Add, select 'Certificates' and select 'Computer Account'
7)Select the Local Computer
8)Now you have two snap-ins:
9)Certificates - Current User
10)Certificates (Local Computer)
11)Now import the certificate in "Certificates (Local Computer)\Trusted Root Certificates\Certificates"

我無法在您的過程中看到您為用於身份驗證的證書添加信任。 false作為參數4傳遞給AuthenticateAsServer()只會跳過檢查吊銷,它一般不會跳過對信任的檢查。

所以你有以下選擇讓它工作:

  • 不要自己生成證書,而是由默認情況下在Windows中受信任的證書頒發機構生成。 這將花費一些錢,但也有一些便宜的CA,它不一定是Thawte證書。
  • 通過將證書導入個人證書列表來添加對證書的信任
  • 如果您已創建已添加到受信任根證書列表(在公司或組織中很常見)的自簽名CA證書,請使用該CA證書簽署證書
  • 根本不進行身份驗證(但可能你不希望這樣)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM