将证书注册到 SSL 端口
Posted
技术标签:
【中文标题】将证书注册到 SSL 端口【英文标题】:Register certificate to SSL port 【发布时间】:2014-12-20 16:07:44 【问题描述】:我有一个自托管 OWIN 服务 (SignalR) 并且需要通过 SSL 访问的 Windows 服务(作为 LocalSystem 运行)。
我可以很好地在我的本地开发机器上设置 SSL 绑定 - 我可以在同一台机器上通过 SSL 访问我的服务。但是,当我转到另一台机器并尝试运行以下命令时,我收到一个错误:
命令:
netsh http add sslcert ipport=0.0.0.0:9389 appid=...guid here... certhash=...cert hash here...
错误:
SSL 证书添加失败,错误:1312
指定的登录会话不存在。它可能已经被终止了。
我使用的证书是完全签名的证书(不是开发证书),可以在我的本地开发盒上运行。这就是我正在做的事情:
Windows 服务启动并使用以下代码注册我的证书:
var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
var path = AppDomain.CurrentDomain.BaseDirectory;
var cert = new X509Certificate2(path + @"\mycert.cer");
var existingCert = store.Certificates.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false);
if (existingCert.Count == 0)
store.Add(cert);
store.Close();
然后我尝试使用 netsh 和以下代码将证书绑定到端口 9389:
var process = new Process
StartInfo = new ProcessStartInfo
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = "/c netsh http add sslcert ipport=0.0.0.0:9389 appid=12345678-db90-4b66-8b01-88f7af2e36bf certhash=" + cert.thumbprint
;
process.Start();
上面的代码成功地将证书安装到“本地计算机 - Certificates\Trusted Root Certification Authorities\Certificates”证书文件夹 - 但 netsh 命令无法运行,并出现上述错误。如果我使用 netsh 命令并在该框中以管理员身份在命令提示符下运行它,它也会抛出相同的错误 - 所以我不认为这是与代码相关的问题......
我不得不想象这是有可能实现的 - 许多其他应用程序创建自托管服务并通过 ssl 托管它们 - 但我似乎根本无法让它工作......有人有什么建议吗?也许是 netsh 的程序化替代品?
【问题讨论】:
我发现如果我在遇到问题的机器上生成一个自签名证书并在该证书的指纹上使用 netsh 它可以工作 - 我想知道是否有办法生成一个自我代码中的签名证书? 您正在从 .cer 文件导入证书,该文件不包含证书的私钥。您需要它的私钥才能将其绑定到端口。要让您的“完全签名证书”正常工作,您需要将它从它所运行的机器(您的开发机器)连同私钥 导出到一个 .pfx 文件中。然后将其导入要安装服务的机器上。在机器上生成自签名证书的原因是因为这会在生成证书的机器上创建一个私钥。 【参考方案1】:好的,我找到了答案:
如果您从另一台机器引入证书,它将无法在新机器上运行。您必须在新机器上创建一个自签名证书并将其导入本地计算机的受信任根证书。
答案来自这里:How to create a self-signed certificate using C#?
为了后代,这是用于创建自签名证书的过程(来自上面引用的答案):
从项目参考中的 COM 选项卡导入 CertEnroll 1.0 类型库
将以下方法添加到您的代码中:
//This method credit belongs to this *** Answer:
//https://***.com/a/13806300/594354
using CERTENROLLLib;
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
// 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;
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
);
对于其他阅读此答案的人 - 从原始问题导入证书的代码现在应更改为以下内容:
var certName = "Your Cert Subject Name";
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)
var cert = CreateSelfSignedCertificate(certName);
store.Add(cert);
RegisterCertForSSL(cert.Thumbprint);
store.Close();
【讨论】:
我会说使用 certutil.exe 比用 C# 编写代码更容易。 我走了那条路,它确实有效 - 但是当您运行 installshield 并尝试执行 certutil 时,您会遇到一堆权限问题......下一个最好的事情是拥有C# 应用程序从在 LocalSystem 下运行的 Windows 服务执行 certutil,但老实说,我更喜欢这种方式,因为它更容易调试 什么是RegisterCertForSSL
‽
这个答案实际上并没有回答这个问题。它讨论了如何创建证书——这不是问题的一部分——然后没有讨论如何将它实际绑定到问题所在的端口。说真的 RegisterCertForSSL(cert.Thumbprint) 是什么?它是某种框架方法吗?它是否涉及第 3 方组件?你写了吗?如果是,那具体是如何工作的?
@RobertPetz 问题是“[如何] 将证书注册到 SSL 端口?”。这个答案没有说明的一件事是如何将证书注册到 SSL 端口因此不,它没有回答问题。【参考方案2】:
这里是完整的代码,包括:
生成证书 在端口上注册 ssl 在该端口上运行简单的 HTTPS 服务器** 请原谅我的代码质量。这只是一个非常肮脏的概念证明,由我在网上找到的不同代码片段和 Robert Petz 的答案粘合而成。我没有时间清理它:
记得
以管理员身份运行 Visual Studio(此代码需要管理员权限) 添加对项目的引用:COM > TypeLibraries > CertEnroll 1.0 类型库代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.SelfHost;
using CERTENROLLLib;
namespace SelfhostSSLProofOfConcept
/// <summary>
/// Add Reference: COM > TypeLibraries > CertEnroll 1.0 Type Library
/// </summary>
class Program
static void Main(string[] args)
var port = 1234;
var certSubjectName = "Your cert subject name";
var expiresIn = TimeSpan.FromDays(7);
var cert = GenerateCert(certSubjectName, expiresIn);
Console.WriteLine("Generated certificate, 0Thumbprint: 10", Environment.NewLine, cert.Thumbprint);
RegisterSslOnPort(port, cert.Thumbprint);
Console.WriteLine($"Registerd SSL on port: port");
var config = new HttpSelfHostConfiguration($"https://localhost:port");
var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());
var task = server.OpenAsync();
task.Wait();
Process.Start($"https://localhost:port"); // automatically run browser
Console.WriteLine($"Web API Server has started at https://localhost:port");
Console.ReadLine();
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;
/// <summary>
/// Add Reference: COM > TypeLibraries > CertEnroll 1.0 Type Library
/// source: https://***.com/a/13806300/594354
/// </summary>
/// <param name="subjectName"></param>
/// <returns></returns>
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
);
class MyWebAPIMessageHandler : HttpMessageHandler
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
var task = new Task<HttpResponseMessage>(() =>
var resMsg = new HttpResponseMessage();
resMsg.Content = new StringContent("Hello World!");
return resMsg;
);
task.Start();
return task;
【讨论】:
以上是关于将证书注册到 SSL 端口的主要内容,如果未能解决你的问题,请参考以下文章
当证书位于使用 netsh 的自定义位置时,如何将证书注册到端口