简体   繁体   English

C# - 实现安全的 Web 套接字

[英]C# - Implement Secure Web Socket

I would like to ask if you know how to implement Secure Web Socket with .Net.我想问您是否知道如何使用.Net 实现安全Web Socket。 I've implemented ws:// and everything ok but I've no idea how to switch to wss://.我已经实现了 ws://,一切正常,但我不知道如何切换到 wss://。 Thanks in advance.提前致谢。

You could try Fleck你可以试试弗莱克

Fleck is a WebSocket server implementation in C# Fleck 是 C# 中的 WebSocket 服务器实现

From their examples:从他们的例子:

var server = new WebSocketServer("wss://0.0.0.0:8431");
server.Certificate = new X509Certificate2("MyCert.pfx");
server.Start(socket =>
{
  //...use as normal
});

This question is very old but here's how i got my C# server accept an SSL connection from the client (js code running on Chrome / Firefox).这个问题很老了,但这是我如何让我的 C# 服务器接受来自客户端的 SSL 连接(在 Chrome/Firefox 上运行的 js 代码)。

Assuming you already have a working and valid certificate (in my case the same certificate working to serve SSL on my Apache webserver), signed by a trusted CA (in my case, letsencrypt.org, which let you request a certificate for free), this is an excerpt from working code:假设您已经拥有一个有效且有效的证书(在我的情况下,该证书在我的 Apache 网络服务器上为 SSL 提供服务),由受信任的 CA 签名(在我的情况下,letsencrypt.org,它允许您免费申请证书),这是工作代码的摘录:

public static X509Certificate2 serverCertificate = null;

public Server(string ip_addr, int port)
{
        serverCertificate = GetCertificateFromStore("CN=mydomain.com");

        string resultsTrue = serverCertificate.ToString(true); // Debugging purposes
        bool hasPrivateKey = serverCertificate.HasPrivateKey; // Debugging purposes (MUST return true)
        Console.WriteLine("Certificate validation results: " + resultsTrue);
        Console.WriteLine("Has private key? " + hasPrivateKey);
        server = new TcpListener(IPAddress.Parse(ip_addr), port);

        server.Start();

        Console.WriteLine("Server has started on ip: " + ip_addr + ":"+port + " - Waiting for a connection...", Environment.NewLine);
 }

 public class ClientHandler
 {
    TcpClient client { get; set; }
    //NetworkStream stream { get; set; } // Old plain non-secure tcp stream
    SslStream stream { get; set; } // New secure tcp stream

    ....

    public ClientHandler(TcpClient client, string room_id)
    {
        ....
        stream = new SslStream(client.GetStream(), false);
        try
        {
            stream.AuthenticateAsServer(Server.serverCertificate, clientCertificateRequired: false, checkCertificateRevocation: false);

            // Set timeouts for the read and write to 5 seconds.
            stream.ReadTimeout = 5000;
            stream.WriteTimeout = 5000;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error during SSL authentication with the client:" + ex);
            return;
        }
    }
}

The tricky part is that class X509Certificate2 needs to retrieve the certificate not from file but from your local keystore.棘手的部分是X509Certificate2类需要不是从文件而是从本地密钥库检索证书。 Also you need both the certificate file AND your private key for SSL to work.您还需要证书文件和您的私钥才能使 SSL 工作。

I'm developing on Linux and Mono.Net but it should not change much on other platforms.我正在 Linux 和 Mono.Net 上开发,但在其他平台上应该不会有太大变化。 The tools i needed were: openssl and certmgr (mono certificate manager).我需要的工具是:openssl 和 certmgr(单声道证书管理器)。

To create the .pfx file containing the cert & the private key:要创建包含证书和私钥的 .pfx 文件:

openssl pkcs12 -export -in yourcertfile.cer -inkey yourprivatekeyfile.pem -out finalfile.pfx

To add the file obtained to my local store:将获得的文件添加到我的本地存储:

certmgr -add -c -m Trust finalfile.pfx 

Finally, you can edit your client side connection code to point to the same domain you're hosting your server (which should be the same domain reported in your certificate).最后,您可以编辑客户端连接代码以指向您托管服务器的同一个域(应该与您的证书中报告的域相同)。

This:这个:

var mySocket = new WebSocket("ws://127.0.0.1:5050");

Becomes:变成:

var mySocket = new WebSocket("wss://yourdomain.com:5050");

Keep in mind that, once you've implemented SSL, you'll have to revise the whole networking code, since you're adding overhead to your TCP stream and you must take it into account when parsing the bytes and the bits to find and decode the headers.请记住,一旦您实施了 SSL,您就必须修改整个网络代码,因为您会增加 TCP 流的开销,并且在解析要查找的字节和位时必须将其考虑在内解码标题。 This is where i'm stuck myself but beside that, SSL connection works great :)这是我被困住的地方,但除此之外,SSL 连接效果很好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM