[英]SslStream.AuthenticateAsServer throws The server mode SSL must use a certificate with the associated private key
[英]SslStream.AuthenticateAsServer exception - The server mode SSL must use a certificate with the associated private key
我正在开发类似于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()?
对于服务器端证书,尽管可以有通配符证书(* .localhost.local),但大多数证书都对应于FQDN(因此为server1.localhost.local)。 当您使用AuthenticateAsClient方法时,这可能是两件事之一:1)证书没有用于客户端身份验证的扩展密钥用法,或者2)您没有通过正确的密码来读取证书/私钥。 为了尽快克服这两个障碍,我建议创建一个OpenSSL CA,然后生成一个CA和服务器证书。 关于如何执行此操作,有大量文档,对于从未创建过证书的人来说,应该花30分钟的时间。...(我也建议将证书导出到pkcs12扩展中,以便将CA与服务器证书链接在一起)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.