我正在开发一个类似于 CCProxy 的代理服务器应用程序。它适用于 HTTP 但不适用于 HTTPS。当在 SslStream 对象上调用 AuthenticateAsServer() 方法时,它会抛出异常。我也不知道我是否提供了正确的证书,我不知道如何创建证书。我刚刚提供了我在网上下载的代码附带的证书。这是代码:
private static void DoHttpProcessing(TcpClient client)
{
Stream clientStream = client.GetStream();
Stream outStream = clientStream;
SslStream sslStream = null;
StreamReader clientStreamReader = new StreamReader(clientStream);
CacheEntry cacheEntry = null;
MemoryStream cacheStream = null;
if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
{
Monitor.TryEnter(_outputLockObj, TimeSpan.FromMilliseconds(-1.0));
}
try
{
//read the first line HTTP command
String httpCmd = clientStreamReader.ReadLine();
if (String.IsNullOrEmpty(httpCmd))
{
clientStreamReader.Close();
clientStream.Close();
return;
}
//break up the line into three components
String[] splitBuffer = httpCmd.Split(spaceSplit, 3);
String method = splitBuffer[0];
String remoteUri = splitBuffer[1];
Version version = new Version(1, 0);
HttpWebRequest webReq;
HttpWebResponse response = null;
if (splitBuffer[0].ToUpper() == "CONNECT")
{
remoteUri = "https://" + splitBuffer[1];
while (!String.IsNullOrEmpty(clientStreamReader.ReadLine())) ;
StreamWriter connectStreamWriter = new StreamWriter(clientStream);
connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
connectStreamWriter.WriteLine("Proxy-agent: matt-dot-net");
connectStreamWriter.WriteLine();
connectStreamWriter.Flush();
sslStream = new SslStream(clientStream, false);
try
{
// HERE I RECEIVE EXCEPTION
sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
sslStream.Close();
clientStreamReader.Close();
connectStreamWriter.Close();
clientStream.Close();
return;
}//further code goes here...
此外,如果我使用 ssStream.AuthenticateAsClient 方法而不是 sslStream.AuthenticateAsServer,则会收到 AuthenticationException 并显示消息“对 SSPI 的调用失败,请参阅内部异常”。并且 InnerException 将消息显示为“收到的消息意外或格式错误”
当我使用 sslstream.AuthenticateAsServer() 方法时,我需要为每个新的 HTTPS 主机创建证书并使用此方法传递它。如果我提供自签名证书,则请求成功。但问题是,对于多少个新的 HTTPS 请求,我将继续手动创建证书并将其分配给 AuthenticateAsServer()?