[英]C# SSL server mode must use a certificate with the corresponding private key
I'm going to learn how to handle HTTPS traffic in C# as server-side and as for the first steps I've got some troubles.我将学习如何在 C# 中作为服务器端处理 HTTPS 流量,至于第一步,我遇到了一些麻烦。
Here is some code ( http://pastebin.com/C4ZYrS8Q ):这是一些代码( http://pastebin.com/C4ZYrS8Q ):
class Program
{
static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None) return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}
static void Main()
{
var tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
tcpListener.Start();
var clientAccept = tcpListener.AcceptTcpClient();
Thread.Sleep(1000);
if (clientAccept.Available > 0)
{
var sslStream = new SslStream(clientAccept.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
var certificate = new X509Certificate("path\server.pfx", "password");
sslStream.AuthenticateAsServer(certificate);
}
Console.ReadLine();
}
}
Don't argue!不要争论! :) It's the test code only where I just want to achieve some basic steps with the SSL handling in C#.
:) 它只是我只想在 C# 中使用 SSL 处理实现一些基本步骤的测试代码。
So... The problem occurs at this line:所以......问题发生在这一行:
sslStream.AuthenticateAsServer(certificate);
From Russian it translates as:从俄语它翻译为:
I thought, that I've made my X509 certificate incorrect, but checked again:我想,我的 X509 证书不正确,但再次检查:
makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx -pi <password>
And seems to be that all is fine with the X509 creation, and other proof is this line works fine:似乎 X509 的创作一切都很好,其他证据表明这条线工作正常:
var certificate = new X509Certificate("path\server.pfx", "password");
And program didn't throw an exception on the line above.并且程序没有在上面的行上抛出异常。
So, what's the problem with the SSL hanlding in my code and how can I handle incoming SSL stream as server-side?那么,我的代码中的 SSL 处理有什么问题,我如何将传入的 SSL 流作为服务器端处理?
All is fine, the answer is to use X509Certificate2
class instead of X509Certificate
.一切都很好,答案是使用
X509Certificate2
类而不是X509Certificate
。
And to add to the trust list your created certificate.并将您创建的证书添加到信任列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.