public static void BindCertificateToPort(this ICertificateConfiguration certificate, string port) { if (certificate == null) { return; } var storeCertificate = certificate.GetX509Certificate(); const string netshGrantAccess = "http add urlacl url=https://+:{0}/ user=EVERYONE"; const string netshAddCertificate = "http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}} clientcertnegotiation=enable"; var grantAccessProcess = new Process { StartInfo = { FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe"), Arguments = string.Format(netshGrantAccess, port) } }; var bindPortToCertificateProcess = new Process { StartInfo = { FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe"), Arguments = string.Format(netshAddCertificate, port, storeCertificate.Thumbprint, Guid.NewGuid()) } }; grantAccessProcess.StartInfo.UseShellExecute = false; grantAccessProcess.StartInfo.RedirectStandardOutput = true; bindPortToCertificateProcess.StartInfo.UseShellExecute = false; bindPortToCertificateProcess.StartInfo.RedirectStandardOutput = true; grantAccessProcess.Start(); CurrentContext.Default.Log.Debug("netsh " + grantAccessProcess.StartInfo.Arguments + " >> " + grantAccessProcess.StandardOutput.ReadToEnd()); grantAccessProcess.WaitForExit(); bindPortToCertificateProcess.Start(); CurrentContext.Default.Log.Debug("netsh " + bindPortToCertificateProcess.StartInfo.Arguments + " >> " + bindPortToCertificateProcess.StandardOutput.ReadToEnd()); bindPortToCertificateProcess.WaitForExit(); }
public static X509Certificate2 GetX509Certificate(this ICertificateConfiguration certificate) { var certStore = new X509Store(certificate.StoreName, certificate.StoreLocation); certStore.Open(OpenFlags.ReadOnly); var certCollection = certStore.Certificates.Find(certificate.FindBy, certificate.Value, false); if (certCollection.Count == 0) { throw new InvalidConfigurationException( string.Format("Could not find the SSL certicate in the store: {0}, location: {1} and {2}: {3}", certificate.StoreName, certificate.StoreLocation, certificate.FindBy, certificate.Value)); } certStore.Close(); CurrentContext.Default.Log.Debug("Using Certificate: " + certCollection[0].Thumbprint); return(certCollection[0]); }