<p><strong>Most recent edits in bold</strong>
I am using the .net <code>HttpListener</code> class, but I won't be running this application on IIS and am not using ASP.net.  This <a href="http://www.leastprivilege.com/CommentView.aspx?guid=0c34094a-bdd4-4041-be6e-919f10fe1d31" rel="noreferrer">web site</a> describes what code to actually use to implement SSL with asp.net and <a href="http://blogs.msdn.com/adarshk/archive/2004/11/10/255467.aspx" rel="noreferrer">this site</a> describes how to set up the certificates (although I'm not sure if it works only for IIS or not).  </p>

<p>The class documentation describes various types of authentication (basic, digest, Windows, etc.) --- none of them refer to SSL.  It does say that if <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx" rel="noreferrer">HTTPS is used, you will need to set a server certificate</a>.  Is this going to be a one line property setting and <code>HttpListener</code> figures out the rest?  </p>

<p>In short, I need to know how to set up the certificates and how to modify the code to implement SSL.</p>

<p>Although it doesn't occur when I'm trying to access HTTPS, I did notice an error in my System Event log - the source is "Schannel" and the content of the message is:</p>

<blockquote>
  <p>A fatal error occurred when attempting
  to access the SSL server credential
  private key. The error code returned
  from the cryptographic module is
  0x80090016.</p>
</blockquote>

<p>Edit:<br>
<strong>Steps taken so far</strong></p>

<ul>
<li>Created a working HTTPListener in C# that works for HTTP connections (e.g. "<a href="http://localhost:8089/foldername/" rel="noreferrer">http://localhost:8089/foldername/</a>"</li>
<li>Created a certificate using makecert.exe</li>
<li>Added the certificate to be trusted using certmgr.exe</li>
<li>Used Httpcfg.exe to listen for SSL connections on a test port (e.g. 8090)</li>
<li>Added port 8080 to the HTTPListener via listener.Prefixes.Add(<a href="https://localhost:8090/foldername/" rel="noreferrer">https://localhost:8090/foldername/</a>");</li>
<li>tested an HTTP client connection, e.g. (<a href="http://localhost:8089/foldername/" rel="noreferrer">http://localhost:8089/foldername/</a>") in a browser and receive correct return</li>
<li>tested an HTTPS client connection, e.g. (<a href="http://localhost:8090/foldername/" rel="noreferrer">http://localhost:8090/foldername/</a>") in a browser and receive "Data Transfer Interrupted" (in Firefox)</li>
<li>debugging in visual studio shows that the listener callback that receives the requests never gets hit when the HTTPS connection starts - I don't see any place that I could set a breakpoint to catch anything else earlier.</li>
<li>netstat shows that listening ports are open for both HTTPS and HTTP.  the HTTPS port does go to TIME_WAIT after a connection is attempted.</li>
<li><strong><a href="http://www.fiddlertool.com/fiddler/" rel="noreferrer">Fiddler</a> and <a href="http://www.ieinspector.com/httpanalyzer/" rel="noreferrer">HTTPAnalyzer</a> don't catch any of the traffic, I guess it doesn't get far enough in the process to show up in those HTTP analysis tools</strong></li>
</ul>

<p><strong>Questions</strong></p>

<ul>
<li>What could the problem be? </li>
<li>Is there a piece of .Net code I am missing (meaning I have to do more in C# other than simply add a prefix to the listener that points to HTTPS, which is what i have done)</li>
<li>Have a missed a configuration step somewhere? </li>
<li>What else might I do to analyze the problem?</li>
<li>Is the error message in the System Event log a sign of the problem?  If so how would it be fixed?</li>
</ul>

[{'answer_id': 4071, 'author': 'pc1oad1etter', 'author_id': 525, 'author_profile': 'https://Stackoverflow.com/users/525', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t have it entirely implemented yet, but this web site seems to give a <a href="http://developers.de/blogs/damir_dobric/archive/2006/08/01/897.aspx" rel="noreferrer">good walkthrough</a> of setting up the certificates and the code.</p>\n'}, {'answer_id': 6116, 'author': 'pc1oad1etter', 'author_id': 525, 'author_profile': 'https://Stackoverflow.com/users/525', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx" rel="nofollow noreferrer">class documentation</a></p>\n\n<p>has this note:</p>\n\n<blockquote>\n  <p>If you create an HttpListener using\n  https, you must select a Server\n  Certificate for that listener.\n  Otherwise, an HttpWebRequest query of\n  this HttpListener will fail with an\n  unexpected close of the connection.</p>\n</blockquote>\n\n<p>and this:</p>\n\n<blockquote>\n  <p>You can configure Server Certificates\n  and other listener options by using\n  HttpCfg.exe. See\n  <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/http/http/httpcfg_exe.asp" rel="nofollow noreferrer">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/http/http/httpcfg_exe.asp</a>\n  for more details. The executable is\n  shipped with Windows Server 2003, or\n  can be built from source code\n  available in the Platform SDK.</p>\n</blockquote>\n\n<p>Is the first note explained by the second?  As outlined in the question, I used httpcfg.exe to bind the certificate to a specific port.  If they intend something other than this, the note is ambiguous.</p>\n'}, {'answer_id': 487143, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve encountered the same issue as you. Fortunately after googling hard steps on <a href="http://answers.google.com/answers/threadview?id=735306" rel="nofollow noreferrer">this page</a> make SSL working with my HttpListener.</p>\n'}, {'answer_id': 727624, 'author': 'galets', 'author_id': 14395, 'author_profile': 'https://Stackoverflow.com/users/14395', 'pm_score': 3, 'selected': False, 'text': '<p>I have a similar problem, and it seems that there could be a problem with certificate itself.</p>\n\n<p>Here\'s the path that worked for me:</p>\n\n<pre><code>makecert.exe -r -a sha1 -n CN=localhost -sky exchange -pe -b 01/01/2000 -e 01/01/2050 -ss my -sr localmachine\n</code></pre>\n\n<p>then look up certificate <a href="http://vvcap.net/db/ci3n4iTr8wYFDF1pJCIO.htp" rel="nofollow noreferrer">thumbprint</a>, copy it to the clipboard and remove spaces. This will be a parameter after -h in the next command:</p>\n\n<pre><code>HttpCfg.exe set ssl -i 0.0.0.0:801 -h 35c65fd4853f49552471d2226e03dd10b7a11755\n</code></pre>\n\n<p>then run a service host on <a href="https://localhost:801/" rel="nofollow noreferrer">https://localhost:801/</a> and it works perfectly.</p>\n\n<p>what I cannot make work is for https to run on self-generated certificate. Here\'s the code I run to generate one (error handling taken out for clarity):</p>\n\n<pre><code>LPCTSTR pszX500 = subject;\nDWORD cbEncoded = 0;\nCertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &amp;cbEncoded, NULL);\npbEncoded = (BYTE *)malloc(cbEncoded);\nCertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &amp;cbEncoded, NULL);\n\n// Prepare certificate Subject for self-signed certificate\nCERT_NAME_BLOB SubjectIssuerBlob;\nmemset(&amp;SubjectIssuerBlob, 0, sizeof(SubjectIssuerBlob));\nSubjectIssuerBlob.cbData = cbEncoded;\nSubjectIssuerBlob.pbData = pbEncoded;\n\n// Prepare key provider structure for self-signed certificate\nCRYPT_KEY_PROV_INFO KeyProvInfo;\nmemset(&amp;KeyProvInfo, 0, sizeof(KeyProvInfo));\nKeyProvInfo.pwszContainerName = _T("my-container");\nKeyProvInfo.pwszProvName = NULL;\nKeyProvInfo.dwProvType = PROV_RSA_FULL;\nKeyProvInfo.dwFlags = CRYPT_MACHINE_KEYSET;\nKeyProvInfo.cProvParam = 0;\nKeyProvInfo.rgProvParam = NULL;\nKeyProvInfo.dwKeySpec = AT_SIGNATURE;\n\n// Prepare algorithm structure for self-signed certificate\nCRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;\nmemset(&amp;SignatureAlgorithm, 0, sizeof(SignatureAlgorithm));\nSignatureAlgorithm.pszObjId = szOID_RSA_SHA1RSA;\n\n// Prepare Expiration date for self-signed certificate\nSYSTEMTIME EndTime;\nGetSystemTime(&amp;EndTime);\nEndTime.wYear += 5;\n\n// Create self-signed certificate\npCertContext = CertCreateSelfSignCertificate(NULL, &amp;SubjectIssuerBlob, 0, &amp;KeyProvInfo, &amp;SignatureAlgorithm, 0, &amp;EndTime, 0);\nhStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"MY");\nCertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, 0);\n</code></pre>\n\n<p>Certificate shows fine and it has a working private key, but https will timeout as if thumbprint was never registered. If anyone knows why - plz comment</p>\n\n<p><strong>EDIT1</strong>: After some playing around, I have found the initialization for CertCreateSelfSignCertificate which generates proper certificate:</p>\n\n<pre><code>CRYPT_KEY_PROV_INFO KeyProvInfo;\nmemset(&amp;KeyProvInfo, 0, sizeof(KeyProvInfo));\nKeyProvInfo.pwszContainerName = _T("my-container");\nKeyProvInfo.pwszProvName = _T("Microsoft RSA SChannel Cryptographic Provider");\nKeyProvInfo.dwProvType = PROV_RSA_SCHANNEL;\nKeyProvInfo.dwFlags = CRYPT_MACHINE_KEYSET;\nKeyProvInfo.cProvParam = 0;\nKeyProvInfo.rgProvParam = NULL;\nKeyProvInfo.dwKeySpec = AT_KEYEXCHANGE;\n</code></pre>\n'}, {'answer_id': 12649776, 'author': 'Despertar', 'author_id': 1160036, 'author_profile': 'https://Stackoverflow.com/users/1160036', 'pm_score': 3, 'selected': False, 'text': "<p>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).</p>\n<p>Run the following with cmd.exe using administrator privileges.</p>\n<pre><code>netsh http add sslcert ipport=0.0.0.0:1234 certhash=613bb67c4acaab06def391680505bae2ced4053b  appid={86476d42-f4f3-48f5-9367-ff60f2ed2cdc}\n</code></pre>\n<p>If you want to create a self-signed certificate to test this,</p>\n<ol>\n<li><p>Open IIS</p>\n</li>\n<li><p>Click on your computer name</p>\n</li>\n<li><p>Click Server Certificates icon</p>\n</li>\n<li><p>Click generate Self-Signed certificate</p>\n</li>\n<li><p>Double click and go to details</p>\n</li>\n<li><p>You will see the thumbprint there, just remove the spaces.</p>\n<pre><code> HttpListener listener = new HttpListener();\n listener.Prefixes.Add(&quot;https://+:1234/&quot;);\n listener.Start();\n Console.WriteLine(&quot;Listening...&quot;);\n HttpListenerContext context = listener.GetContext();\n\n using (Stream stream = context.Response.OutputStream)\n using (StreamWriter writer = new StreamWriter(stream))\n     writer.Write(&quot;hello, https world&quot;);\n\n Console.ReadLine();\n</code></pre>\n</li>\n</ol>\n<p>After running this program I just navigated to <code>https://localhost:1234</code> 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.</p>\n<p>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.</p>\n<hr />\n<p>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.</p>\n<pre><code>ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) =&gt; true;\n</code></pre>\n"}, {'answer_id': 28803107, 'author': 'Steven de Salas', 'author_id': 448568, 'author_profile': 'https://Stackoverflow.com/users/448568', 'pm_score': 2, 'selected': False, 'text': '<p>Here is an alternative way to bind the SSL certifiate to the IP/PORT combination without using <code>httpcfg.exe</code> (XP) or <code>netsh.exe</code> (Vista+).</p>\n\n<p><a href="http://dotnetcodebox.blogspot.com.au/2012/01/how-to-work-with-ssl-certificate.html" rel="nofollow">http://dotnetcodebox.blogspot.com.au/2012/01/how-to-work-with-ssl-certificate.html</a></p>\n\n<p>The gist of it is that you can use a C++ <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364503(v=vs.85).aspx" rel="nofollow">HttpSetServiceConfiguration</a> API in-built into windows to do it programatically rather than via the command line, hence removing dependency on the OS and having httpcfg installed.</p>\n'}]
['https://Stackoverflow.com/questions/4004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525/']