1

I have some code that is supposed to add an ssl certifacate to a port. It does say it has succesfully added a certificate, but when i host the website and then type in the localhost url (localhost:{port}) the page keeps loading. I don't understand why it doesn't work.

I already tried to host the website without ssl and that worked fine so that's not the problem.

public static class Certificate
{
    public static void Standard(int port)
    {
        var certSubjectName = "HelloMyNameIsHank";
        var expiresIn = TimeSpan.FromHours(1);
        var cert = GenerateCert(certSubjectName, expiresIn);

        Console.WriteLine("Generated certificate, {0}Thumbprint: {1}{0}", Environment.NewLine, cert.Thumbprint);

        RegisterSslOnPort(port, cert.Thumbprint);
        Console.WriteLine($"Registerd SSL on port: {port}");
    }

    private static void RegisterSslOnPort(int port, string certThumbprint)
    {
        var appId = Guid.NewGuid();
        string arguments = $"http add sslcert ipport=0.0.0.0:{port} certhash={certThumbprint} appid={{{appId}}}";
        ProcessStartInfo procStartInfo = new ProcessStartInfo("netsh", arguments);

        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;

        var process = Process.Start(procStartInfo);
        while (!process.StandardOutput.EndOfStream)
        {
            string line = process.StandardOutput.ReadLine();
            Console.WriteLine(line);
        }

        process.WaitForExit();
    }

    public static X509Certificate2 GenerateCert(string certName, TimeSpan expiresIn)
    {
        var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadWrite);
        var existingCert = store.Certificates.Find(X509FindType.FindBySubjectName, certName, false);
        if (existingCert.Count > 0)
        {
            store.Close();
            return existingCert[0];
        }
        else
        {
            var cert = CreateSelfSignedCertificate(certName, expiresIn);
            store.Add(cert);

            store.Close();
            return cert;
        }
    }

    public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expiresIn)
    {
        // create DN for subject and issuer
        var dn = new CX500DistinguishedName();
        dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);

        // create a new private key for the certificate
        CX509PrivateKey privateKey = new CX509PrivateKey();
        privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
        privateKey.MachineContext = true;
        privateKey.Length = 2048;
        privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited
        privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
        privateKey.Create();

        // Use the stronger SHA512 hashing algorithm
        var hashobj = new CObjectId();
        hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
            ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
            AlgorithmFlags.AlgorithmFlagsNone, "SHA512");

        // add extended key usage if you want - look at MSDN for a list of possible OIDs
        var oid = new CObjectId();
        oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
        var oidlist = new CObjectIds();
        oidlist.Add(oid);
        var eku = new CX509ExtensionEnhancedKeyUsage();
        eku.InitializeEncode(oidlist);

        // Create the self signing request
        var cert = new CX509CertificateRequestCertificate();
        cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
        cert.Subject = dn;
        cert.Issuer = dn; // the issuer and the subject are the same
        cert.NotBefore = DateTime.Now;
        // this cert expires immediately. Change to whatever makes sense for you
        cert.NotAfter = DateTime.Now.Add(expiresIn);
        cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
        cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
        cert.Encode(); // encode the certificate

        // Do the final enrollment process
        var enroll = new CX509Enrollment();
        enroll.InitializeFromRequest(cert); // load the certificate
        enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
        string csr = enroll.CreateRequest(); // Output the request in base64
        // and install it back as the response
        enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
            csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
        // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
        var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
            PFXExportOptions.PFXExportChainWithRoot);

        // instantiate the target class with the PKCS#12 data (and the empty password)
        return new System.Security.Cryptography.X509Certificates.X509Certificate2(
            System.Convert.FromBase64String(base64encoded), "",
            // mark the private key as exportable (this is usually what you want to do)
            System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
        );
    }
}

I want to be able to host my website with https. If anyone knows why this doesn't work please tell me.

I'm using httplistener for hosting. I don't want to use ASP.NET and/or IIS.

I'm not to familiar with ssl certificates so I would also really appreciate some code snippets even if it's just pseudo-code.

  • Took a quick look at code and it looks like most of the code is loading the certificate on machine. See if this code project helps : https://www.codeproject.com/Articles/838276/Web-API-Thoughts-of-Working-with-HTTPS – jdweng May 11 '19 at 22:10
  • I don't want to use ASP.NET or IIS –  May 12 '19 at 11:29
  • IIIS is just the machine code is used on and has nothing to do with the code. I don't see anything on the posting to do with ASP. – jdweng May 12 '19 at 13:38
  • each part of this page either contains ASP.NET or IIS –  May 12 '19 at 17:40
  • The IIS just requires a Certificate because it is secure and is no different that any other secure server that is not IIS. All the code shown on the main page is c# which can be called from ASP, but also can be used without ASP. If you look at the source code most of it is simply c#. ASP code is JSON. – jdweng May 12 '19 at 17:53
  • Hosting is done in runtime i don't use any hosting software –  May 13 '19 at 16:45
  • c# code is c# code. The code can still be used. Do not confuse the methods needed to solve your issue with the application where the code is used. It is like using same c# code in a Console application and a Form Application. Console code can be used in a Form, but not all Form code can be used in a Console. – jdweng May 13 '19 at 17:32
  • I have recently implement HTTPS using HTTPListener. There is no any input required, everything is handled by C# code. I have shared my solution here: https://stackoverflow.com/a/58149405/983548 – Habib Sheikh Sep 28 '19 at 21:01

0 Answers0