1

我正在尝试使用 WebSocketSharp 在客户端/服务器之间发送和验证 SSL 证书

服务器端

wss = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 6070, true);
string _certificatePath = Path.GetDirectoryName(typeof(WSS_Server).Assembly.Location) + "\\cert\\public_privatekey.pfx";
wss.SslConfiguration.ServerCertificate = new X509Certificate2(_certificatePath, "mypass");
wss.SslConfiguration.ClientCertificateRequired = false; // true;
wss.SslConfiguration.CheckCertificateRevocation = false; // true;
wss.SslConfiguration.ClientCertificateValidationCallback = RemoteCertificateValidationCallback;

wss.AddWebSocketService<MyRemoteService>(
"/myservice",
() => new MyRemoteService()
{
    OriginValidator = val =>
    {
        // Check the value of the Origin header, and return true if valid.
        return true;
    },
    CookiesValidator = (req, res) =>
    {
        return true; // If valid.
    }

});

客户端

var ws = new WebSocket("wss://127.0.0.1:6070/myservice/");
string _certificatePath = "\\cert\\public_privatekey.pfx";
X509Certificate2 x509 = new X509Certificate2(_certificatePath, "mypass");
X509CertificateCollection xcol = new X509CertificateCollection();
xcol.Add(x509);

ws.SslConfiguration = new WebSocketSharp.Net.ClientSslConfiguration("127.0.0.1", xcol, System.Security.Authentication.SslProtocols.Default, false);
//ws.SslConfiguration.ClientCertificates = new X509CertificateCollection();
//ws.SslConfiguration.ClientCertificates.Add(x509);

ws.OnOpen += Ws_OnOpen;
ws.OnMessage += Ws_OnMessage;
ws.OnError += Ws_OnError;
ws.OnClose += Ws_OnClose;
ws.Connect();

在服务器端 RemoteCertificateValidationCallback证书始终为

就像客户端从不发送证书一样。

知道如何解决吗?

4

3 回答 3

3

这里没有一个答案对我有用。为了使其工作,我需要设置SslConfiguration.ClientCertificateSelectionCallback一个适当的值,如下所示:

X509Certificate2 cert = new X509Certificate2(fileName, "", X509KeyStorageFlags.MachineKeySet);
ws.SslConfiguration.ClientCertificateSelectionCallback =
            (sender,targethost,localCertificates, remoteCertificate,acceptableIssuers) =>
            {
                return cert;
            };

事实上,WebsocketSharp 源代码中的文档清楚地说明了:SslConfiguration.ClientCertificateSelectionCallback

获取或设置用于选择要提供给服务器的证书的回调。如果回调返回 null ,则不提供证书。[...]默认值是调用仅返回 null 的方法的委托。

因此,如果您没有在此回调中明确提供客户端证书,则不会发送任何证书。

于 2019-06-11T12:32:47.653 回答
0

我有同样的问题我解决了

X509Certificate2 cert = new X509Certificate2(fileName, "", X509KeyStorageFlags.MachineKeySet);
ws.SslConfiguration.ClientCertificates = new X509CertificateCollection() { };
ws.SslConfiguration.ClientCertificates.Add(cert);
于 2019-04-29T09:59:40.293 回答
0

您始终可以设置或获取包含客户端证书的集合WebSocketSharp

为此,您可以将X509Certificate2对象添加到ClientCertificates.

干得好:

var ws = new WebSocket("wss://127.0.0.1:6070/myservice/");
string _certificatePath = "\\cert\\public_privatekey.pfx";
X509Certificate2 x509 = new X509Certificate2(_certificatePath, "mypass");    
ws.SslConfiguration.ClientCertificates.Add(x509);
ws.Connect();

然后您可以在服务器端验证此证书。希望这将是您问题的答案。

于 2018-10-29T11:37:57.090 回答