簡體   English   中英

如何使用證書身份驗證自定義套接字TCP協議?

[英]How to use certificate authentication for custom sockets TCP protocol?

我知道WCF有證書身份驗證。 如何為自定義套接字協議執行相同的操作? 我應該使用哪些類來驗證證書? 我應該在各方之間轉移什么數據? 有哪些必要步驟?

假設您要使用SSL:

在服務器端,您可以將NetworkStream包裝在SslStream並使用X509Certificate身份驗證:

SslStream stream = new SslStream(networkStream, false);
stream.AuthenticateAsServer(certificate, false, SslProtocols.Default, false);

第二個調用中的false控制服務器是否還要求客戶端擁有證書。

此鏈接包含生成自簽名證書的代碼,在開發過程中很方便。

在客戶端,您必須提供驗證回調:

SslStream stream = new SslStream(networkStream, false, ValidateRemoteCertificate);
stream.AuthenticateAsClient(RemoteHost);

如果需要,您可以在AuthenticateAsClient重載中提供客戶端證書。

private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        return true;
    }

    // Here you decide whether self-signed certificates are OK
    if (allowAnyCertificateAnyway)
    {
        return true;
    }

    return false;
}

我希望這會有所幫助,它使用的是NetworkStream ,它最終只是Socket一個包裝器。 這都是在框架中內置的,您可以從/向SslStream讀取/寫入,就像它是常規的NetworkStream

暫無
暫無

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

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