Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何以编程方式为WCF服务创建自签名证书?_C#_.net_Certificate_Wcf Security_Self Signed - Fatal编程技术网

C# 如何以编程方式为WCF服务创建自签名证书?

C# 如何以编程方式为WCF服务创建自签名证书?,c#,.net,certificate,wcf-security,self-signed,C#,.net,Certificate,Wcf Security,Self Signed,我有一个自托管的WCF服务器,在本地系统帐户下作为Windows服务运行。我试图用c语言编程创建一个自签名证书,用于使用消息级安全性的net.tcp端点 我正在使用下面的代码,这是非常密切的基础上接受的答案,在一些小的变化,试图解决我的问题 public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expirationLength) { // create DN for

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

我正在使用下面的代码,这是非常密切的基础上接受的答案,在一些小的变化,试图解决我的问题

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服务时,出现以下异常:

证书“CN=myCertificate”可能没有能够进行密钥交换的私钥,或者进程可能没有私钥的访问权限。有关详细信息,请参见内部异常。 内部异常:键集不存在

我的证书的FindPrivateKey示例()的输出为:

Private key directory:
C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
Private key file name:
f0d47c7826b8ef5148b6d412f1c40024_4a8a026f-58e4-40f7-b779-3ae9b6aae1a7
我可以在资源管理器中看到这个1.43KB的文件。如果我查看属性|安全性,我会看到系统和管理员都拥有完全控制权

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

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

如果我使用MakeCert创建证书,它从一开始就可以正常工作。我不知道它有什么不同

另一条可能不相关的信息是,证书不仅会被放在我告诉它要放的My store中,还会被放在“中级证书颁发机构”的store中。我不知道为什么,也不知道这是否重要

那么…你知道我做错了什么吗

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

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对象。所以这似乎是同样的问题。同样,在我打开证书的“管理私钥”对话框之后,这也可以很好地工作

我仍在寻找问题的原因

更新#2:我能够使用下面公认的答案来实现这一点。有趣的是,该代码现在似乎将证书放在机器存储中,而不调用X509Store代码。我仍然调用代码,因为我不确定,它不会伤害任何东西。这是我用来创建证书的最后一段代码

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

我不能使这项工作,但我找到了另一种解决办法。(2014年12月更新:我现在已使用公认的答案使其工作。)

我能够利用这个机会来实现我所需要的。我不得不稍微修改源代码,以便将私钥存储在LocalMachine存储中。我所做的更改是对CryptContext.cs文件的。我更改了CreateSelfSignedCertificate方法。下面是一段代码,包括我所做的更改。本质上,如果CryptContext对象的标志中包含此值,我将CryptKeyProviderInformation结构的Flags成员设置为0x20(CRYPT_MACHINE_KEYSET)

        byte[] asnName = properties.Name.RawData;
        GCHandle asnNameHandle = GCHandle.Alloc(asnName, GCHandleType.Pinned);

        int flags = 0;                    // New code
        if ((this.Flags & 0x20) == 0x20)  // New code
            flags = 0x20;                 // New code

        var kpi = new Win32Native.CryptKeyProviderInformation
        {
            ContainerName = this.ContainerName,
            KeySpec = (int)KeyType.Exchange,
            ProviderType = 1, // default RSA Full provider
            Flags = flags                 // New code
        };
然后我在自己的代码中使用该函数,如下所示:

        using (Pluralsight.Crypto.CryptContext ctx = new Pluralsight.Crypto.CryptContext()) {

            ctx.Flags = 0x8 | 0x20;
            ctx.Open();

            X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
                new Pluralsight.Crypto.SelfSignedCertProperties
                {
                    IsPrivateKeyExportable = true,
                    KeyBitLength = 4096,
                    Name = new X500DistinguishedName("CN=" + subjectName),
                    ValidFrom = DateTime.Today,
                    ValidTo = DateTime.Today + expirationLength,
                });

            return cert;
        }
注意,我将CryptContext对象的标志设置为0x8 | 0x20(CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET)


我希望我能找出我原来的解决方案出了什么问题。但是我需要一些工作,在我的测试中,这个解决方案满足了我的需要。我希望它能帮助其他人。

我在PowerShell中使用等效代码时也遇到了同样的问题。有时私钥似乎消失了。我使用了进程监视器,您可以看到密钥文件被删除


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

您也可以使用CodePlex()上的CLR安全库。下面是创建自签名证书的示例代码,并使用SSLStream对其进行测试

        var machineName = Environment.MachineName;
        var keyCreationParameters = new CngKeyCreationParameters();
        keyCreationParameters.KeyUsage = CngKeyUsages.AllUsages;
        keyCreationParameters.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
        keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(4096), CngPropertyOptions.None));
        var cngKey = CngKey.Create(CngAlgorithm2.Rsa, "Test", keyCreationParameters);

        var x500DistinguishedName = new X500DistinguishedName("CN=" + machineName);
        x500DistinguishedName.Oid.Value = "1.3.6.1.5.5.7.3.1";
        var certificateCreationParameters = new X509CertificateCreationParameters(x500DistinguishedName);
        certificateCreationParameters.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512;
        certificateCreationParameters.TakeOwnershipOfKey = true;
        certificateCreationParameters.CertificateCreationOptions = X509CertificateCreationOptions.None;
        certificateCreationParameters.EndTime = new DateTime(9999, 12,31, 23, 59, 59, 999, DateTimeKind.Utc);
        var certificate = cngKey.CreateSelfSignedCertificate(certificateCreationParameters);

        var certificateStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
        certificateStore.Open(OpenFlags.ReadWrite);
        certificateStore.Add(certificate);
        certificateStore.Close();


        var tcpListener = TcpListener.Create(6666);
        tcpListener.Start();
        var client = new TcpClient("localhost", 6666);
        var acceptedClient = tcpListener.AcceptTcpClient();
        var acceptedClinetSslStream = new SslStream(
            acceptedClient.GetStream(), false);
        var serverAuthTask = acceptedClinetSslStream.AuthenticateAsServerAsync(certificate,
                            false, SslProtocols.Tls, true);

        SslStream clientSslStream = new SslStream(
            client.GetStream(),
            false,
            delegate(object o, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors errors)
                {
                    if (errors == SslPolicyErrors.None)
                        return true;

                    Console.WriteLine("Certificate error: {0}", errors);

                    // Do not allow this client to communicate with unauthenticated servers. 
                    return false;
                },
            null);
        var clientAuthTask = clientSslStream.AuthenticateAsClientAsync(machineName);

        Task.WaitAll(serverAuthTask, clientAuthTask);

谢谢你的回答。我有一个有效的解决方案,我不愿意改变它。我现在没有时间测试这个答案,但如果我测试了,我会回来把它标记为被接受的答案。一年后,我终于检查了这个答案,它成功了!我将PersistKeySet标志添加到构造函数中,并且该键不会消失。我更新了我的原始帖子以显示工作代码。请问在哪里可以找到这些CryptContext标志?我找不到任何文档。您可以在此处找到标志的文档:以及此处的数字标志值:有人知道如何使用友好名称加载现有证书吗?感谢提供更新。。我有一个类似的问题,无法指出我做错了什么,你在这篇文章中帮了我很多忙!:)