c# - HTTPS代理

时间:2016-03-24 11:36:24

标签: c# ssl https proxy server

我试图在c#中创建HTTPS代理服务器。 有人在这里发布了一个解决方案:

        string host = "encrypted.google.com";
        string proxy = "127.0.0.1";//host;
        int proxyPort = 8888;//443;

        byte[] buffer = new byte[2048];
        int bytes;

        // Connect socket
        TcpClient client = new TcpClient(proxy, proxyPort);
        NetworkStream stream = client.GetStream();

        // Establish Tcp tunnel
        byte[] tunnelRequest = Encoding.UTF8.GetBytes(String.Format("CONNECT {0}:443  HTTP/1.1\r\nHost: {0}\r\n\r\n", host));
        stream.Write(tunnelRequest , 0, tunnelRequest.Length);
        stream.Flush();

        // Read response to CONNECT request
        // There should be loop that reads multiple packets
        bytes = stream.Read(buffer, 0, buffer.Length);
        Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));

        // Wrap in SSL stream
        SslStream sslStream = new SslStream(stream);
        sslStream.AuthenticateAsClient(host);

        // Send request
        byte[] request = Encoding.UTF8.GetBytes(String.Format("GET https://{0}/  HTTP/1.1\r\nHost: {0}\r\n\r\n", host));
        sslStream.Write(request, 0, request.Length);
        sslStream.Flush();

        // Read response
        do
        {
            bytes = sslStream.Read(buffer, 0, buffer.Length);
            Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));
        } while (bytes != 0);

        client.Close();
        Console.ReadKey();

但是,这不是服务器的代码。它打印响应(作为纯文本),但客户端套接字(浏览器)没有得到响应。

感谢您的帮助, 感谢。

1 个答案:

答案 0 :(得分:0)

我不是C#专家,但不会用对原始CONNECT请求来自的TCP连接的写操作替换Console.Write来解决此问题?

看起来好像缺少一些代码,就像在发生所有这些事情之前,您必须通过TCP连接监听客户端。因此,例如,您正在侦听IP地址192.168.1.1端口8080。然后客户端发送类似

的内容

HTTP / 1.1 www.example.com:443

然后您去做所有这些事情,然后要执行(192.168.1.1:8080).write()或等同于C#的工作,而不是Console.write。