将证书注册到SSL端口 [英] Register certificate to SSL port
问题描述
我有一个Windows服务(以LocalSystem运行),该服务自托管OWIN服务(SignalR),需要通过SSL进行访问.
I have a windows service (running as LocalSystem) that is self-hosting an OWIN service (SignalR) and needs to be accessed over SSL.
我可以在本地开发计算机上很好地设置SSL绑定-并且可以在同一台计算机上通过SSL访问我的服务.但是,当我转到另一台计算机并尝试运行以下命令时,会收到错误消息:
I can set up the SSL binding on my local development machine just fine - and I can access my service over SSL on that same machine. However, when I go to another machine and try to run the following command I receive an error:
命令:
netsh http add sslcert ipport=0.0.0.0:9389 appid={...guid here...} certhash=...cert hash here...
错误:
SSL证书添加失败,错误:1312
SSL Certificate add failed, Error: 1312
指定的登录会话不存在.它可能已经终止了.
A specified logon session does not exist. It may have already been terminated.
我正在使用的证书是完全签名的证书(不是开发证书),并且可以在我的本地开发箱中使用.这是我在做什么:
The certificate I am using is a fully signed cert (not a development cert) and works on my local dev box. Here's what I am doing:
Windows服务启动,并使用以下代码注册我的证书:
Windows service starts up and registers my certificate using the following code:
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:
I then attempt to bind the certificate to port 9389 using netsh and the following code:
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();
上面的代码已成功将证书安装到本地计算机-证书\受信任的根证书颁发机构\证书"证书文件夹中-但netsh命令无法运行,并出现上述错误.如果我执行netsh命令并以管理员身份在该框上的命令提示符下运行它,还会抛出相同的错误-因此,我不认为这是与代码相关的问题...
The code above successfully installs the certificate to the "Local Machine - Certificates\Trusted Root Certification Authorities\Certificates" certificate folder - but the netsh command fails to run with the error I described above. If I take the netsh command and run it in a command prompt as an administrator on that box it also throws out the same error - so I don't believe that it's a code related issue...
我必须想象这是有可能实现的-许多其他应用程序创建了自托管服务并将它们托管在ssl上-但我似乎无法使它完全起作用...有人有什么建议吗?也许是netsh的编程替代品?
I have to imagine that this is possible to accomplish - plenty of other applications create self-hosted services and host them over ssl - but I cannot seem to get this to work at all...anyone have any suggestions? Perhaps programmatic alternatives to netsh?
推荐答案
好的,我找到了答案:
如果从另一台计算机上引入证书,则该证书将无法在新计算机上运行.您必须在新计算机上创建一个自签名证书,并将其导入到本地计算机的受信任的根证书中.
If you are bringing in a certificate from another machine it will NOT work on the new machine. You have to create a self-signed certificate on the new machine and import it into the Local Computer's Trusted Root Certificates.
答案来自这里:如何使用C#创建自签名证书?
为了后代的缘故,这是用于创建自签名证书的过程(根据上述参考答案):
For posterity's sake this is the process used to create a self signed cert (from the above referenced answer):
从项目引用的"COM"选项卡中导入CertEnroll 1.0类型库
Import the CertEnroll 1.0 Type Library from the COM tab in your project's references
在您的代码中添加以下方法:
Add the following method to your code:
//This method credit belongs to this StackOverflow Answer:
//https://stackoverflow.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
);
}
对于任何其他阅读此答案的人-从原始问题中导入证书的代码现在应更改为以下内容:
For anyone else reading this answer - the code for importing the certificate from the original question should now change to the following:
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();
这篇关于将证书注册到SSL端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!