我正在制作代理服务器。我使用Implementing a Multithreaded HTTP/HTTPS Debugging Proxy Server in C#作为参考。
这段代码:
private void ProccessRequest(Socket client)
{
// Create network stream from socket for read and write data
Stream networkStream = new NetworkStream(client, true);
// Create stream reader for read data from socket
StreamReader clientReader = new StreamReader(networkStream);
// For read and write data to socket
// Same for http and https requests
Stream clientStream = networkStream;
try
{
if (client.Connected)
{
// Get first request line
string str = clientReader.ReadLine();
if (!String.IsNullOrEmpty(str))
{
string[] tmpStr = str.Split(SapceSplit, 3);
String method = tmpStr[0];
String remoteUrl = tmpStr[1];
if (method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase))
{
remoteUrl = "https://" + remoteUrl;
// Read all information from socket
while (!String.IsNullOrEmpty(clientReader.ReadLine())) ;
// Tell browser that connection established
StreamWriter connectWriter = new StreamWriter(networkStream);
connectWriter.WriteLine("HTTP/1.0 200 Connection established");
connectWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
connectWriter.WriteLine();
connectWriter.Flush();
// Create SSL stream
SslStream sslStream = new SslStream(networkStream, false);
// Set sertificate for decrypt the client's traffic
sslStream.AuthenticateAsServer(_certificate, false,
SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
// HTTPS server created - we can now decrypt the client's traffic
clientReader = new StreamReader(sslStream);
clientStream = sslStream;
// read the new http command.
str = clientReader.ReadLine();
tmpStr = str.Split(SapceSplit, 3);
method = tmpStr[0].ToUpper();
remoteUrl = remoteUrl + tmpStr[1];
}
但是就这一行:
sslStream.AuthenticateAsServer(_certificate, false,
SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
我收到错误:身份验证失败,因为远程方已关闭传输流。
我正在使用私钥加载证书:
_certificate = new X509Certificate2("D:\\cert2.pfx", "1234", X509KeyStorageFlags.MachineKeySet);