簡體   English   中英

使用Mono安全API在C#中生成證書策略擴展

[英]Generating Certificate Policies Extension In C# Using Mono Security API

我很高興能在此問題上提出任何建議,這使我發瘋,並且找不到任何文獻資料。 我目前正在嘗試使用滿足某些要求(RSA 2048,SHA256,Etc)的單聲道安全性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也很靈活,這也是可以接受的解決方案。 預先感謝您的任何幫助。

在搜尋了多個源之后,我能夠通過從Mono切換到Microsoft的certenroll.dll來解決此問題。 我的用於通過Policy Extensions生成自簽名證書的代碼如下。 希望這可以幫助任何有類似問題的人。

基於以下參考的代碼: http : //technet.microsoft.com/zh-cn/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
        );

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM