How do I add SSL to a .net application that uses httplistener - it will *not* be running on IIS

前端 未结 6 1235
無奈伤痛
無奈伤痛 2020-12-12 20:57

Most recent edits in bold I am using the .net HttpListener class, but I won\'t be running this application on IIS and am not using ASP.net. Th

6条回答
  •  半阙折子戏
    2020-12-12 21:11

    You just have to bind a certificate to an ip:port and then open your listener with an https:// prefix. 0.0.0.0 applies to all ip's. appid is any random GUID, and certhash is the hash of the certificate (sometimes called a thumprint).

    Run the following with cmd.exe using administrator privileges.

    netsh http add sslcert ipport=0.0.0.0:1234 certhash=613bb67c4acaab06def391680505bae2ced4053b  appid={86476d42-f4f3-48f5-9367-ff60f2ed2cdc}
    

    If you want to create a self-signed certificate to test this,

    1. Open IIS

    2. Click on your computer name

    3. Click Server Certificates icon

    4. Click generate Self-Signed certificate

    5. Double click and go to details

    6. You will see the thumbprint there, just remove the spaces.

       HttpListener listener = new HttpListener();
       listener.Prefixes.Add("https://+:1234/");
       listener.Start();
       Console.WriteLine("Listening...");
       HttpListenerContext context = listener.GetContext();
      
       using (Stream stream = context.Response.OutputStream)
       using (StreamWriter writer = new StreamWriter(stream))
           writer.Write("hello, https world");
      
       Console.ReadLine();
      

    After running this program I just navigated to https://localhost:1234 to see the text printed. Since the certificate CN does not match the url and it is not in the Trusted Certificate store you will get a Certificate Warning. The text is encrypted however as you can verify with a tool like Wire Shark.

    If you want more control over creating a self-signed x509 certificate openssl is a great tool and there is a port for windows. I've had a lot more success with it than the makecert tool.


    It's also very important that to if you are communicating with an https service from code that has an ssl warning, you must setup the certificate validator on the service point manager to bypass it for testing purposes.

    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
    

提交回复
热议问题