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

时间:2014-01-24 12:50:29

标签: 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");

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

这是迟到的,但我认为问题是你不能保留私钥。在证书创建的最后一行

return new X509Certificate2(Convert.FromBase64String(base64encoded), "",X509KeyStorageFlags.Exportable);

你没有设置" X509KeyStorageFlags.PersistKeySet"。这会导致私钥保留在您正在创建的新证书中。否则......证书安装时没有私钥。

尝试:

return new X509Certificate2(Convert.FromBase64String(base64encoded), "",X509KeyStorageFlags.Exportable |  X509KeyStorageFlags.PersistKeySet);

我没有经营它......所以不能保证。

将X509Certificate2从文件添加到商店也是如此。构造X509Certificate2时,必须传递X509KeyStorageFlags.PersistKeySet标志以使其保留私钥。我知道这个(从文件加载)肯定,因为我花了很多时间进行故障排除。