0

I found a lot of answers how to set httplistener up to use HTTPS, but each one solution requires the use of command line. I guess that is the fastest way to do it but I would like to write C# class to handle this.

In old solution I used webserver class (found somewhere on Internet, I don't remember exact name) which allowed to add certificate in that way:

webserver.Certificate = new X509Certificate2("MyCert.pfx", "MyPassword");

Is there way to achieve this with httplistener? From code obviously.

Regards.

Adam Mrozek
  • 1,098
  • 3
  • 20
  • 38
  • What command line command are you trying to duplicate in C#? Seems like you should start by making your http listener work, using the That way you'll know *exactly* what setup commands you need to duplicate in C# code. – Jim Mischel Feb 07 '14 at 14:05
  • My httplistener works perfectly but my employer insists on encrypted connection. This solution ( http://stackoverflow.com/questions/11403333/httplistener-with-https-support ) contains all I need to do. – Adam Mrozek Feb 07 '14 at 14:16

1 Answers1

5

You can load a certificate with:

X509Certificate cert = new X509Certificate2("MyCert.pfx");

And then install it:

X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
if (!store.Certificates.Contains(cert))
{
    store.Add(cert);
}
store.Close();

Of course you might have to change the store name or location for your particular app.

For running the netsh command, you could look into creating and running a process (i.e. Process.Start) and run netsh.exe. Otherwise you have to mess with the Win32 HttpSetServiceConfiguration function, or the .NET equivalent if there is one.

You might find this codebox article useful: http://dotnetcodebox.blogspot.com/2012/01/how-to-work-with-ssl-certificate.html

Erwin Mayer
  • 15,942
  • 9
  • 79
  • 117
Jim Mischel
  • 122,159
  • 16
  • 161
  • 305
  • I have published the code from the blog as a [Nuget package](https://www.nuget.org/packages/SslCertBinding.Net/). Feel free to use it. Example of full certificate installation can be found in [unit tests](https://github.com/segor/SslCertBinding.Net/blob/master/src/SslCertBinding.Net.Sample.Tests/UnitTests.cs) – Serghei Gorodetki Jun 04 '15 at 13:01