4

I use SslStream to build a web server. However, the code below throws an exception when AuthenticateAsServer.

static X509Certificate cert;
protected virtual Stream GetStream(TcpClient client)
{
        var ss = new SslStream(client.GetStream(), false);
        if (cert == null)
        {
            cert = X509Certificate2.CreateFromCertFile("test.cer");
        }
        ss.AuthenticateAsServer(cert, false, System.Security.Authentication.SslProtocols.Tls, true);
        return ss;
}

I've already used X509Certificate2 to load the cert file why it still throw the exception (The server mode SSL must use a certificate with the associated private key)?

The cert file was created using the following command:

makecert    
    -pe                                     Exportable private key
    -n "CN=localhost"                       Subject name
    -ss my                                  Certificate store name
    -sr LocalMachine                        Certificate store location
    -a sha1                                 Signature algorithm
    -sky signature                          Subject key type is for signature purposes
    -r                                      Make a self-signed cert
    "test.cer"                            Output filename
Mark Yuan
  • 850
  • 1
  • 8
  • 17

1 Answers1

6
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>

var certificate = new X509Certificate("path\server.pfx", "password");
Mark Yuan
  • 850
  • 1
  • 8
  • 17
  • Thanks this works fine, I had to use new X509Certificate2 though (not X509Certificate) – Drakarah Oct 02 '15 at 19:28
  • `Error: Unable to create file for the subject ('server.pvk')`. Windows has a UI for everything, they couldn't make a button to this in 1 second? – The Muffin Man May 28 '17 at 01:13