问题描述
我要学习如何处理HTTPS在C#作为服务器端,并作为我有一些麻烦的第一个步骤的流量。
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.
下面是一些代码():
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();
}
}
不要争辩! :)这只是测试代码,我只是想实现与SSL在C#中处理一些基本的步骤
Don't argue! :) It's the test code only where I just want to achieve some basic steps with the SSL handling in C#.
所以...该这条线出现问题:
So... The the problem occurs at this line:
sslStream.AuthenticateAsServer(certificate);
这是俄罗斯将其翻译为:
- SSL服务器模式必须使用证书具有相应的私钥
From Russian it translates as: - SSL server mode must use a certificate with the corresponding private key.
我想,我已经做了我的X509证书不正确,但再次检查:
I thought, that I've made my X509 certificate incorrect, but checked again:
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>
和似乎是,所有的罚款与X509创作和其他证明是这条线工作正常
And seems to be that all is fine with the X509 creation, and other proof is this line works fine:
var certificate = new X509Certificate("path\server.pfx", "password");
和方案没有扔在上面的行例外。
And program didn't throw an exception on the line above.
那么,什么是在我的代码SSL hanlding问题,我该怎么处理传入的SSL数据流服务器端?
So, what's the problem with the SSL hanlding in my code and how can I handle incoming SSL stream as server-side?
推荐答案
一切都很好,得到的答案是使用 X509Certificate2
类,而不是 X509证书
。
All is fine, the answer is to use X509Certificate2
class instead of X509Certificate
.
和添加到信任列表中创建的证书。
And to add to the trust list your created certificate.
这篇关于C#SSL服务器模式必须使用证书具有相应的私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!