c# - 在 WCF 中使用创建自签名证书

标签 c# wcf x509certificate2

您好,我有一个使用自签名证书的 wcf 服务。以前的版本没有安全性,我只在新版本中实现它。但我需要更新旧版本的程序。这就是为什么我需要在代码中创建证书并添加到商店。我使用来自 1 个答案的代码 How to create a self-signed certificate using C#?小改动的例子

public class CertificateTools
{
    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.KeyProtection = X509PrivateKeyProtection.XCN_NCRYPT_UI_NO_PROTECTION_FLAG;
        privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
        privateKey.MachineContext = true;
        privateKey.Length = 1024;
        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, "SHA1");

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


        //KeyUseg
        CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsage();
        // Key Usage Extension 
        extensionKeyUsage.InitializeEncode(
            X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE |
            X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE |
            X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE
        );


        // 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.AddYears(-1);
        // this cert expires immediately. Change to whatever makes sense for you
        cert.NotAfter = DateTime.Now.AddYears(100);
        cert.X509Extensions.Add((CX509Extension) extensionKeyUsage);//add the KU
        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 X509Certificate2(Convert.FromBase64String(base64encoded), "",X509KeyStorageFlags.Exportable);
    }
}

和代码

        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);
        var certificate = CertificateTools.CreateSelfSignedCertificate("ServerAdminService");     
        store.Add(certificate);           
        store.Close();

使用代码

         scb = new ServiceCredentials();
         scb.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ServerAdminService");

这会创建证书并添加它,但是当我尝试使用它时发生错误。报错中说没有私钥或者进程没有权限。看起来我需要更改一些标志,但我不知道是哪个。

最佳答案

没有看到添加到商店的证书。看看这是否有帮助,

store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);
    var certificate = CertificateTools.CreateSelfSignedCertificate("ServerAdminService");   
    store.Add(certificate ) ;            
    store.Close();

关于c# - 在 WCF 中使用创建自签名证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21333209/

相关文章:

C# 查询没有被执行

c# - 在 C# : what iteration is this? 中调试 foreach 循环

.net - 无法访问 WCF 中的已处置对象异常

c# - 服务器宕机时的异常或http状态码

wcf - 通过 channel 接口(interface)支持消息级安全性的最小客户端

c# - 无法通过通用名称从 C# 中的存储中获取证书

c# - 使用 WebSocketClient ReceiveAsync 和缓冲区的正确方法是什么?

C# 正则表达式过滤器

c# - RazorEngine 3.7.7 - 编译缓存模板时出错

c# - 将私钥导出为字节数组的最佳方式