1

我很感激我能在这个问题上提供的任何建议,它一直让我发疯,我找不到任何文档。我目前正在尝试使用满足某些要求(RSA 2048、SHA256 等)的单声道安全 API 在 C# 中生成自签名根证书。我已经成功地生成了一个满足所有这些要求的证书,但只有一个。

我正在尝试添加一个 CertificatePoliciesExtension 这些扩展通常在 X509 证书中格式化如下

[4]: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
 [CertificatePolicyId: [some policy oid]
    [PolicyQualifierInfo: 
       [qualifierID: some qualifier oid
         qualifier: some ascii encoded byte stream]]]]

我的代码如下:

private void GenerateRootCertMono(RSACryptoServiceProvider rsa, byte[] serialNumber, string password)
    {
         // default values
        string subject = "CN= company name";
        string issuer = "CN=company name";
        DateTime notBefore = DateTime.Now;
        DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z


        X509CertificateBuilder cb = new X509CertificateBuilder(3);
        cb.SerialNumber = serialNumber;
        cb.IssuerName = issuer;
        cb.NotBefore = notBefore;
        cb.NotAfter = notAfter;
        cb.SubjectName = subject;
        cb.SubjectPublicKey = rsa;
        // extensions
        BasicConstraintsExtension bce = new BasicConstraintsExtension();
        bce.CertificateAuthority = true;
        cb.Extensions.Add(bce);
        KeyUsageExtension kue = new KeyUsageExtension();
        kue.KeyUsage = KeyUsages.digitalSignature ;

        KeyUsageExtension kue1 = new KeyUsageExtension();
        kue1.KeyUsage = KeyUsages.keyCertSign;

       //my failed attempt to generate a simple Certificate Policy Extension
       **ASN1 a = new ASN1 ();
        a.Add(ASN1Convert.FromOid("2.5.29.32"));
        a.Add(ASN1Convert.FromOid("some oid"));
        a.Add(new ASN1 (System.Text.Encoding.ASCII.GetBytes("some text")));
        CertificatePoliciesExtension pce = new CertificatePoliciesExtension(a); 


        cb.Extensions.Add(pce);
        cb.Extensions.Add(kue);
        cb.Extensions.Add(kue1);
    // signature
        cb.Hash = "SHA256";
        byte[] rawcert = cb.Sign(rsa);
        X509Certificate2 pfx = new X509Certificate2(rawcert);
        pfx.PrivateKey = rsa;
        this.PFX = pfx.Export(X509ContentType.Pkcs12, password);
        return;
  }

我知道生成这些扩展是可能的,因为我在其他证书中看到过它们。有没有人有任何经验或建议?如果有人知道如何在 C# 中使用 MSCAPI 生成这些扩展,我对 API 也很灵活,例如这也是一个可接受的解决方案。预先感谢您的任何帮助。

4

1 回答 1

1

在搜索了多个来源之后,我能够通过从 Mono 切换到 Microsoft 的 certenroll.dll 来解决这个问题。下面是使用 Policy Extensions 生成自签名证书的代码。希望这可以帮助任何有类似问题的人。

基于以下参考的代码: http ://technet.microsoft.com/en-us/library/ff182332(v=ws.10).aspx 。

    public X509Certificate2 CreateSelfSignedCert(string subject,string password,DateTime expDate)
    {
        // create DN for subject and issuer
        var dn = new CX500DistinguishedName();
       // dn.Encode("CN=" + subject, X500NameFlags.XCN_CERT_NAME_STR_NONE);
        dn.Encode(subject, X500NameFlags.XCN_CERT_NAME_STR_NONE);

        // create a new private key for the certificate
        CX509PrivateKey privateKey = new CX509PrivateKey();
        privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0";
        privateKey.MachineContext = true;
        privateKey.Length = 2048;
        privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited
        privateKey.ExportPolicy
            = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
        privateKey.Create();

        // Use Sha256 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,
            "SHA256");

        // Create the self signing request
        var cert = new CX509CertificateRequestCertificate();
        cert.InitializeFromPrivateKey(
            X509CertificateEnrollmentContext.ContextMachine,
            privateKey,
            string.Empty);

        cert.Subject = dn;
        cert.Issuer = dn; // the issuer and the subject are the same
        cert.NotBefore = DateTime.Now;
        cert.NotAfter = expDate;
        cert.HashAlgorithm = hashobj;

        // extensions 
        CX509ExtensionKeyUsage ku = new CX509ExtensionKeyUsage();
        ku.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE);
        ku.Critical = true;
        cert.X509Extensions.Add((CX509Extension)ku);

        CX509ExtensionBasicConstraints bc = new CX509ExtensionBasicConstraints();
        bc.InitializeEncode(true,0);
        bc.Critical = false;
        cert.X509Extensions.Add((CX509Extension)bc);


        // Add the certificate policy.
        CObjectId cpOid = new CObjectId();
        cpOid.InitializeFromValue("some oid");
        CCertificatePolicy cp = new CCertificatePolicy();
        CPolicyQualifier Qualifier = new CPolicyQualifier();
        Qualifier.InitializeEncode("Policy Notice", PolicyQualifierType.PolicyQualifierTypeUserNotice);
        cp.Initialize(cpOid);
        cp.PolicyQualifiers.Add(Qualifier);
        CCertificatePolicies cps = new CCertificatePolicies();
        cps.Add(cp);
        CX509ExtensionCertificatePolicies cpExt = new CX509ExtensionCertificatePolicies();
        cpExt.InitializeEncode(cps);
        cert.X509Extensions.Add((CX509Extension)cpExt);



        // Do the final enrollment process
        var enroll = new CX509Enrollment();
        enroll.InitializeFromRequest(cert); // load the certificate
        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( "", 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
            System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
        );

    }
于 2013-07-24T21:19:10.167 回答