Reputation: 14399
I'm trying to create a test client/server connection using the following code:
static void Main(string[] args)
{
var listenerThread = new Thread(ListenerThreadEntry);
listenerThread.Start();
Thread.Sleep(TimeSpan.FromSeconds(1));
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect("localhost", Port);
var rawStream = new NetworkStream(socket);
var stream = new SslStream(rawStream, false, VerifyServerCertificate);
var certificate = new X509Certificate(CertsPath + @"test.cer");
var certificates = new X509CertificateCollection(new[] { certificate });
stream.AuthenticateAsClient("localhost", certificates, SslProtocols.Tls, false);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
private static bool VerifyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
static void ListenerThreadEntry()
{
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = listener.AcceptTcpClient();
var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
var sslStream = new SslStream(client.GetStream(), false);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false);
Thread.Sleep(TimeSpan.FromSeconds(10));
}
And getting "The remote certificate is invalid according to the validation procedure" error message in the AuthenticateAsServer method. Certificate was created and saved to file using these commands:
makecert.exe -r -pe -n "CN=localhost" -a sha1 -sky exchange -sv test.pvk test.cer
pvk2pfx -pvk test.pvk -spc test.cer -pfx test.pfx
What have I missed?
Upvotes: 12
Views: 2645
Reputation: 59208
I can't see where in your process you add trust to the certificate you use for authentication. Passing false
as parameter 4 to AuthenticateAsServer()
only skips the check for revocation, it does not skip the check for trust in general.
So you have the following choices to make it work:
Upvotes: 2
Reputation:
check these steps, seems to be working,
1)First save the certificate in a file
2)Run MMC
3)Open the Certificate Manager (certmgr.msc in C:\Windows\System32)
4)You will see it opens 'Certificates - Current User'
5)In the menu, choose File, Add/Remove Snap-In
6)Now press Add, select 'Certificates' and select 'Computer Account'
7)Select the Local Computer
8)Now you have two snap-ins:
9)Certificates - Current User
10)Certificates (Local Computer)
11)Now import the certificate in "Certificates (Local Computer)\Trusted Root Certificates\Certificates"
Upvotes: 3