C# 将证书注册到SSL端口

C# 将证书注册到SSL端口,c#,.net,.net-4.5,owin,self-hosting,C#,.net,.net 4.5,Owin,Self Hosting,我有一个windows服务(以LocalSystem运行),它是OWIN服务(SignalR)的自宿主,需要通过SSL进行访问 我可以在本地开发机器上设置SSL绑定,并且可以在同一台机器上通过SSL访问我的服务。但是,当我转到另一台计算机并尝试运行以下命令时,我收到一个错误: 命令: netsh http add sslcert ipport=0.0.0.0:9389 appid={...guid here...} certhash=...cert hash here... 错误: SSL证书

我有一个windows服务(以LocalSystem运行),它是OWIN服务(SignalR)的自宿主,需要通过SSL进行访问

我可以在本地开发机器上设置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();
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和以下代码将证书绑定到端口9389:

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();
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();
上面的代码成功地将证书安装到“Local Machine-Certificates\Trusted Root certificate Authorities\Certificates”证书文件夹中,但是netsh命令无法运行,出现了上面描述的错误。如果我使用netsh命令并以管理员的身份在命令提示符下运行它,它也会抛出相同的错误-因此我不认为这是一个与代码相关的问题


我不得不想象这是可能实现的——许多其他应用程序创建自托管服务并通过ssl托管它们——但我似乎根本无法实现这一点……有人有什么建议吗?也许是netsh的编程替代方案?

好的,我找到了答案:

如果您从另一台计算机引入证书,它将无法在新计算机上工作。您必须在新计算机上创建自签名证书,并将其导入本地计算机的受信任根证书

答案就在这里:

为子孙后代着想,这是用于创建自签名证书的过程(根据上述参考答案):

从项目引用中的COM选项卡导入CertEnroll 1.0类型库

将以下方法添加到代码中:

//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
    );
}
对于阅读此答案的其他人-从原始问题导入证书的代码现在应更改为以下代码:

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
  • 在该端口上运行简单的HTTPS服务器
**请原谅我的代码质量。这只是一个非常肮脏的概念证明,由我在网上找到的不同代码片段粘合而成,Robert Petz给出了答案。我没有时间清理它:

记住

  • 以管理员身份运行Visual Studio(此代码需要管理员权限)
  • 添加对项目的引用:COM>TypeLibraries>CertEnroll 1.0类型库
代码:

使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用System.IO;
使用System.Linq;
使用System.Net.Http;
使用System.Security.Cryptography.X509证书;
使用系统文本;
使用System.Threading.Tasks;
使用System.Web.Http.SelfHost;
使用证书库;
名称空间selfhostsslproofconcept
{
/// 
///添加引用:COM>类型库>CertEnroll 1.0类型库
/// 
班级计划
{
静态void Main(字符串[]参数)
{
var端口=1234;
var certSubjectName=“您的证书主体名称”;
var expiresIn=时间跨度从天(7);
var cert=GenerateCert(certSubjectName,expiresIn);
WriteLine(“生成的证书,{0}指纹:{1}{0}”,Environment.NewLine,cert.Thumbprint);
注册表slonport(端口、证书指纹);
WriteLine($“端口上的注册SSL:{port}”);
var config=新的HttpSelfHostConfiguration($)https://localhost:{port}”);
var server=new-HttpSelfHostServer(配置,new-MyWebAPIMessageHandler());
var task=server.OpenAsync();
task.Wait();
进程启动($)https://localhost:{port}”);//自动运行浏览器
Console.WriteLine($)Web API服务器已在启动https://localhost:{port}”);
Console.ReadLine();
}
专用静态无效寄存器slonport(int端口,字符串证书指纹)
{
var appId=Guid.NewGuid();
字符串参数=$“http add sslcert ipport=0.0.0:{port}certhash={certThumbprint}appid={{{{appid}}}”;
ProcessStartInfo procStartInfo=新的ProcessStartInfo(“netsh”,参数);
procStartInfo.RedirectStandardOutput=true;
procStartInfo.UseShellExecute=false;
procStartInfo.CreateNoWindow=true;
var process=process.Start(procStartInfo);
而(!process.StandardOutput.EndOfStream)
{
string line=process.StandardOutput.ReadLine();
控制台写入线(行);
}
process.WaitForExit();
}
公共静态X509Certificate2 GenerateCert(字符串certName,TimeSpan expiresIn)
{
var store=new X509Store(StoreName.Root,StoreLocation.LocalMachine);
打开(OpenFlags.ReadWrite);
var existingCert=store.Certificates.Find(X509FindType.FindBySubjectName,certName,false);
如果(现有证书计数>0)
{
store.Close();
返回现有证书[0];
}
其他的
{
var cert=CreateSelfSignedCertificate(certName,expiresIn);
存储。添加(证书);
store.Close();
返回证书;
}
}
/// 
///添加引用:COM>类型库>CertEnroll 1.0类型库
///资料来源:https://stackoverflow.com/a/13806300/594354
/// 
/// 
/// 
公共静态X509Certificate2 CreateSelfSignedCertific