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

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

问题描述

我有一个自托管的WCF服务器上运行的本地系统帐户下一个Windows服务。我想创建一个自签名证书以编程方式在C#与一个端点的net.tcp通过使用消息级安全性。

我使用下面的code这是非常密切的基础上,<一个公认的答案href="http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c">How使用C#创建自签名的证书?的一些小的改动试图解决我的问题。

 公共静态X509Certificate2 CreateSelfSignedCertificate(字符串subjectName,时间跨度expirationLength)
{
    //创建DN为主体和发行人
    变种DN =新CX500DistinguishedName();
    dn.En code(CN =+ subjectName,X500NameFlags.XCN_CERT_NAME_STR_NONE);

    CX509PrivateKey privateKey =新CX509PrivateKey();
    privateKey.ProviderName =微软强加密提供程序;
    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();

    //使用更强的SHA512散列算法
    VAR hashobj =新CObjectId();
    hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HAS​​H_ALG_OID_GROUP_ID,
        ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
        AlgorithmFlags.AlgorithmFlagsNone,SHA1);

    //创建自签名请求
    VAR证书=新CX509CertificateRequestCertificate();
    cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine,privateKey,);
    cert.Subject = DN;
    cert.Issuer = DN; //发行人的主体是相同的
    cert.NotBefore = DateTime.Now.Date;
    //这个证书立即失效。切换到任何有意义的你
    cert.NotAfter = cert.NotBefore + expirationLength;
    //cert.X509Extensions.Add((CX509Extension)eku); //添加EKU
    cert.HashAlgorithm = hashobj; //指定的哈希算法
    cert.En code(); // EN code证书

    //做最后的注册流程
    VAR登记=新CX509Enrollment();
    enroll.InitializeFromRequest(证书); //加载证书
    enroll.CertificateFriendlyName = subjectName; //可选:添加一个友好的名称
    字符串CSR = enroll.CreateRequest(); //输出为Base64请求
    //并安装它作为响应返回
    enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
        企业社会责任,EncodingType.XCN_CRYPT_STRING_BASE64,); //没有密码
    //输出一个base64连接codeD PKCS#12,所以我们可以将其导入回.NET安全类
    VAR base64en codeD = enroll.CreatePFX(,//没有密码,这是为国内消费
        PFXExportOptions.PFXExportChainWithRoot);

    //与PKCS实例化目标类#12的数据(和空密码)
    返回新System.Security.Cryptography.X509Certificates.X509Certificate2(
        System.Convert.FromBase64String(base64en codeD),,
        //标记为可导出私钥(这通常是你想要做什么)
        //标记专用键进入当前用户存储进计算机存储,而不是
        X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet
    );
}
 

和我存放与此code:

 的X509Store店=新的X509Store(STORENAME,StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(newCert);
store.Close();
 

这将创建证书,并把它在LOCALMACHINE证书存储区。问题是,当我尝试启动WCF服务,我得到以下异常:

这是可能的证书CN = myCertificate'可能没有一个私钥能够密钥交换或过程中不得有私钥的访问权限。请查看详细的内部异常。 内部异常:键集不存在

在FindPrivateKey样品的输出( HTTP ://msdn.microsoft.com/en-us/library/aa717039%28v=vs.100%29.aspx )对我的证书是:

 私钥目录:
C:\ ProgramData \微软\加密\ RSA \ MachineKeys的
私有密钥文件名:
f0d47c7826b8ef5148b6d412f1c40024_4a8a026f-58e4-40f7-b779-3ae9b6aae1a7
 

我可以看到在资源管理器这个1.43KB文件。如果我看看属性|安全我看到系统和管理员都与完全控制

在研究这个错误我已经看到了关于私有密钥丢失或不正确的权限很多答案。我看不出有什么问题。

真正奇怪的是,如果我使用MMC证书插件,去该证书,选择所有任务|管理私钥......我看到了相同的安全设置。以后即使我只是弹出对话框,然后按下取消按钮证书现在正常WCF中查看此。我可以简单地重新启动该服务,一切都运行完美。

如果我创建使用MakeCert证书它的作品从一开始就好了。我不知道它的作用是不同的。

另外一个片可能不相关的信息是,该证书不仅被摆在我的店里,我叫他去找放,但它也将被放置在中级证书颁发机构存储。我不知道为什么,或者如果它很重要。

所以...任何想法是我做错了吗?

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

 密码参数:
    供应商名称:微软软件密钥存储提供
    算法名称:不适用。
    项名称:{A23712D0-9A7B-4377-89DB-B1B39E3DA8B5}
    主要类型:机械键。

加密操作:
    操作:开关键。
    返回code:0x80090011
 

0x80090011是找不到对象。因此,这似乎是同样的问题。同样,当我打开管理私钥对话框的证书,这个完美的作品也。

我还在寻找问题的原因。

更新#2:我可以使用下面的接受的答案得到这个工作。有趣的是,code现在似乎把在计算机存储的证书,而不调用的X509Store code。我还是叫了code,因为我不知道,它不会伤害任何东西。下面是我用来创建证书的最后code。

 静态公共X509Certificate2 CreateSelfSignedCertificate(字符串subjectName,时间跨度expirationLength)
    {
        //创建DN为主体和发行人
        变种DN =新CX500DistinguishedName();
        dn.En code(CN =+ subjectName,X500NameFlags.XCN_CERT_NAME_STR_NONE);

        CX509PrivateKey privateKey =新CX509PrivateKey();
        privateKey.ProviderName =微软强加密提供程序;
        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();

        //使用更强的SHA512散列算法
        VAR hashobj =新CObjectId();
        hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HAS​​H_ALG_OID_GROUP_ID,
            ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
            AlgorithmFlags.AlgorithmFlagsNone,SHA512);

        //创建自签名请求
        VAR证书=新CX509CertificateRequestCertificate();
        cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine,privateKey,);
        cert.Subject = DN;
        cert.Issuer = DN; //发行人的主体是相同的
        cert.NotBefore = DateTime.Now.Date;
        //这个证书立即失效。切换到任何有意义的你
        cert.NotAfter = cert.NotBefore + expirationLength;
        cert.HashAlgorithm = hashobj; //指定的哈希算法
        cert.En code(); // EN code证书

        //做最后的注册流程
        VAR登记=新CX509Enrollment();
        enroll.InitializeFromRequest(证书); //加载证书
        enroll.CertificateFriendlyName = subjectName; //可选:添加一个友好的名称
        字符串CSR = enroll.CreateRequest(); //输出为Base64请求
        //并安装它作为响应返回
        enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
            企业社会责任,EncodingType.XCN_CRYPT_STRING_BASE64,); //没有密码
        //输出一个base64连接codeD PKCS#12,所以我们可以将其导入回.NET安全类
        VAR base64en codeD = enroll.CreatePFX(,//没有密码,这是为国内消费
            PFXExportOptions.PFXExportChainWithRoot);

        //与PKCS实例化目标类#12的数据(和空密码)
        返回新System.Security.Cryptography.X509Certificates.X509Certificate2(
            System.Convert.FromBase64String(base64en codeD),,
            //标记为可导出私钥(这通常是你想要做什么)
            //标记专用键进入当前用户存储进计算机存储,而不是
            X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
        );
    }
 

解决方案

我不得不使用等效code在PowerShell中同样的问题。看来,有时私钥就这样消失。我用进程监视器,你可以看到被删除的密钥文件。

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

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
    );
}

And I store it with this code:

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

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:

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

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

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.

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.

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?

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 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: 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
        );
    }

解决方案

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.

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

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

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