如何以编程方式为WCF服务创建自签名证书? [英] How to create self-signed certificate programmatically for WCF service?

查看:326
本文介绍了如何以编程方式为WCF服务创建自签名证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自行托管的WCF服务器作为Windows服务运行在本地系统帐户下。我试图在c#中以编程方式创建一个自签名证书,以便与使用消息级别安全性的net.tcp端点一起使用。

I have a self-hosted WCF server running as a Windows service under the Local System account. I am trying to create a self-signed certificate programmatically in c# for use with a net.tcp endpoint using Message level security.

我使用以下代码密切基于中接受的答案。如何创建自签名

I am using the following code which is very closely based on the accepted answer in How to create a self-signed certificate using C#? with some small changes trying to solve my problem.

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

    CX509PrivateKey privateKey = new CX509PrivateKey();
    privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
    privateKey.Length = 1024;
    privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
    privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
    privateKey.MachineContext = true;
    privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_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, "SHA1");

    // 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.Date;
    // this cert expires immediately. Change to whatever makes sense for you
    cert.NotAfter = cert.NotBefore + expirationLength;
    //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)
        // mark private key to go into the Machine store instead of the current users store
        X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet
    );
}

我用这个代码存储:

X509Store store = new X509Store(storeName, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(newCert);
store.Close();

这将创建证书并将其放在LocalMachine证书存储中。问题是,当我尝试启动WCF服务时,我得到以下异常:

This creates the certificate and puts it in the LocalMachine certificate store. The problem is that when I try to start the WCF service I get the following exception:

很可能证书CN = myCertificate可能没有私钥能够进行密钥交换,或者该过程可以不具有对于私钥的访问权限。有关详细信息,请参阅内部异常。
内部异常:密钥集不存在

It is likely that certificate 'CN=myCertificate' may not have a private key that is capable of key exchange or the process may not have access rights for the private key. Please see inner exception for detail. Inner exception: Keyset does not exist

FindPrivateKey示例的输出( http://msdn.microsoft.com/en-us/library/aa717039%28v=vs.100%29.aspx )for我的证书是:

The output of the FindPrivateKey sample (http://msdn.microsoft.com/en-us/library/aa717039%28v=vs.100%29.aspx) for my certificate is:

Private key directory:
C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
Private key file name:
f0d47c7826b8ef5148b6d412f1c40024_4a8a026f-58e4-40f7-b779-3ae9b6aae1a7


$ b b

我可以在浏览器中看到这个1.43KB的文件。如果我看看属性|安全我看到SYSTEM和管理员两个完全控制。

I can see this 1.43KB file in explorer. If I look at the properties|Security I see SYSTEM and Administrators both with Full control.

在研究这个错误,我看到许多答案有关私钥丢失或不正确的权限。我不能看到问题是什么。

In researching this error I have seen many answers about the private key missing or incorrect permissions. I can't see what the problem is.

真奇怪的是,如果我使用mmc证书插件,请去证书,选择所有任务|管理私人键...我看到相同的安全设置。在查看这个即使我只是打开对话框,并按下取消按钮证书现在可以正常工作在WCF。我可以简单地重新启动服务,一切运行完美。

The really strange thing is that if I use the mmc Certificate plugin, go to the certificate and choose All Tasks|Manage Private Keys... I see the same security settings. After viewing this even if I just bring up the dialog and hit the Cancel button the certificate now works correctly in WCF. I can simply restart the service and everything runs perfectly.

如果我使用MakeCert创建一个证书,它从一开始就很好。我不知道它有什么不同。

If I create a certificate using MakeCert it works just fine from the start. I don't know what it does differently.

另一个可能不相关的信息是,证书不仅被放在我的商店它得到放,但它也被放入中级认证机构商店。

One other piece of information that may not be relevant is that the certificate not only gets put in the My store where I told it to get put, but it also gets put in the "Intermediate Certification Authorities" store. I don't know why or if it matters.

所以...任何想法我做错了什么?

So...any ideas what I am doing wrong?

更新:嗯,这不只是一个WCF问题。我基本上得到相同的问题,当我尝试使用证书绑定到http.sys使用 HttpSetServiceConfiguration 。该方法返回1312 - 指定的登录会话不存在,它可能已经终止。这实际上不是真正的错误。我在安全事件日志中看到一个审计失败,说:

UPDATE: Well, this is not just a WCF issue. I essentially get the same problem when I try to use the certificate to bind to an endpoint with http.sys using HttpSetServiceConfiguration. The method returns 1312 - "A specified logon session does not exist. It may already have been terminated". This is actually not the real error. I saw in the Security Event log an Audit Failure that say this:

Cryptographic Parameters:
    Provider Name:  Microsoft Software Key Storage Provider
    Algorithm Name: Not Available.
    Key Name:   {A23712D0-9A7B-4377-89DB-B1B39E3DA8B5}
    Key Type:   Machine key.

Cryptographic Operation:
    Operation:  Open Key.
    Return Code:    0x80090011

0x80090011未找到Object。所以这似乎是同样的问题。再次,在我为证书打开管理私钥对话框后,这也很好。

0x80090011 is Object was not found. So this appears to be the same problem. Again, after I open the Manage Private Keys dialog for the certificate this works perfectly also.

我仍然在寻找问题的原因。

I am still looking for the cause of the problem.

UPDATE#2:我能够使用下面接受的答案得到这个工作。有趣的是,这个代码现在似乎把证书放在Machine存储中,而不调用X509Store代码。我仍然调用代码,因为我不知道,它不伤害任何东西。这是我用来创建证书的最终代码。

UPDATE #2: I was able to get this working using the accepted answer below. Interestingly, this code now seems to put the certificate in the Machine store without calling the X509Store code. I still call the code because I am not sure and it does not hurt anything. Here is the final code that I am using to create the certificate.

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

        CX509PrivateKey privateKey = new CX509PrivateKey();
        privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
        privateKey.Length = 2048;
        privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
        privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
        privateKey.MachineContext = true;
        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");

        // 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.Date;
        // this cert expires immediately. Change to whatever makes sense for you
        cert.NotAfter = cert.NotBefore + expirationLength;
        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)
            // mark private key to go into the Machine store instead of the current users store
            X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
        );
    }


推荐答案

PowerShell中的等效代码。看来有时私钥刚好消失了。我使用Process Monitor,你可以看到正在删除的密钥文件。

I had the same issue using the equivalent code in PowerShell. It appears that sometime the private key just disappears. I used Process Monitor and you can see the key file being deleted.

我解决这个问题的方法是添加 X509KeyStorageFlags.PersistKeySet 到X509Certificate2构造函数。

The way I solved this was to add X509KeyStorageFlags.PersistKeySet to the X509Certificate2 constructor.

这篇关于如何以编程方式为WCF服务创建自签名证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆