Exemple #1
0
 /// <summary>
 /// Add a given extension field for the standard extensions tag (tag 0)
 /// </summary>
 /// <param name="oid">The object identifier identifying the extension type.</param>
 /// <param name="critical">true if the extension should be regarded as critical, false otherwise.</param>
 /// <param name="extensionValue">The ASN.1 object to be encoded as the extension's value.</param>
 public void AddExtension(
     DerObjectIdentifier oid,
     bool critical,
     Asn1Encodable extensionValue)
 {
     extGenerator.AddExtension(oid, critical, extensionValue);
 }
Exemple #2
0
        private X509ExtensionsGenerator GetExtensionsGenerator(string[] altnames)
        {
            X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();

            var(basicConstrainsCritical, basicConstraintsExt) = GetBasicConstraints();
            var(keyUsageCritical, keyUsageExt)       = GetKeyUsage();
            var(extKeyUsageCritical, extKeyUsageExt) = GetExtendedUsage();
            var(altNamesCritical, altNamesExt)       = GetSubjectAltName(altnames);

            if (basicConstraintsExt != null)
            {
                extGenerator.AddExtension(X509Extensions.BasicConstraints, basicConstrainsCritical, basicConstraintsExt);
            }
            if (keyUsageExt != null)
            {
                extGenerator.AddExtension(X509Extensions.KeyUsage, keyUsageCritical, keyUsageExt);
            }
            if (extKeyUsageExt != null)
            {
                extGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, extKeyUsageCritical, extKeyUsageExt);
            }
            if (altNamesExt != null)
            {
                extGenerator.AddExtension(X509Extensions.SubjectAlternativeName, altNamesCritical, altNamesExt);
            }

            return(extGenerator);
        }
Exemple #3
0
        /// <summary>
        /// Get an X509Extensions object containing all extensions from the request
        /// </summary>
        /// <returns>List of extension (or null)</returns>
        private X509Extensions getExtensions()
        {
            if (Attributes == null)
            {
                return(null);
            }

            DerObjectIdentifier ExtensionsOid = new DerObjectIdentifier("1.2.840.113549.1.9.14");

            if (attributes.ContainsKey(ExtensionsOid))
            {
                X509ExtensionsGenerator gen = new X509ExtensionsGenerator();
                bool critical;
                foreach (DerSequence outer in attributes[ExtensionsOid])
                {
                    foreach (DerSequence inner in outer)
                    {
                        // Note that the extension value is wrapped in an OctetString, but the generator expects an unwrapped value
                        if (inner.Count == 3)                        // Critical flag set
                        {
                            critical = isTrue((DerBoolean)inner[1]); // Just in case it is false
                            gen.AddExtension((DerObjectIdentifier)inner[0], critical, ((DerOctetString)inner[2]).GetOctets());
                        }
                        else                       // Count==2; Critical flag not set
                        {
                            gen.AddExtension((DerObjectIdentifier)inner[0], false, ((DerOctetString)inner[1]).GetOctets());
                        }
                    }
                }

                return(gen.Generate());
            }
            return(null);
        }
Exemple #4
0
        public void Read_WithExtensions_ReturnsInstance()
        {
            var extensionsGenerator = new X509ExtensionsGenerator();

            extensionsGenerator.AddExtension(
                new DerObjectIdentifier("1.2.3.4.5.1"), critical: true, extValue: new byte[1] {
                1
            });
            extensionsGenerator.AddExtension(
                new DerObjectIdentifier("1.2.3.4.5.2"), critical: false, extValue: new byte[1] {
                2
            });

            var extensions = extensionsGenerator.Generate();
            var test       = new Test()
            {
                Extensions = extensions
            };
            var bcTstInfo = test.CreateBcTstInfo();

            var tstInfo = TstInfo.Read(bcTstInfo.GetDerEncoded());

            Verify(test, tstInfo);
            Verify(bcTstInfo, tstInfo);
        }
 /// <summary>Add a given extension field for the standard extensions tag.</summary>
 public void AddExtension(
     string oid,
     bool critical,
     Asn1Encodable extensionValue)
 {
     extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
 }
Exemple #6
0
        /// <summary>
        /// Gets the <see cref="OcspResp"/> for the <see cref="OcspReq"/>
        /// </summary>
        /// <param name="ocspRequest"></param>
        /// <param name="issuerCertificate"></param>
        /// <returns></returns>
        private async Task <OcspResp> GetOcspDefinitiveResponse(OcspReq ocspRequest, X509Certificate issuerCertificate)
        {
            var basicResponseGenerator = new BasicOcspRespGenerator(
                new RespID(
                    await OcspResponderRepository.GetResponderPublicKey(issuerCertificate)));

            var extensionsGenerator = new X509ExtensionsGenerator();

            var nextUpdate = await OcspResponderRepository.GetNextUpdate();

            foreach (var request in ocspRequest.GetRequestList())
            {
                var certificateId = request.GetCertID();
                var serialNumber  = certificateId.SerialNumber;

                CertificateStatus   certificateStatus;
                CaCompromisedStatus caCompromisedStatus = await OcspResponderRepository.IsCaCompromised(issuerCertificate);

                if (caCompromisedStatus.IsCompromised)
                {
                    // See section 2.7 of RFC 6960
                    certificateStatus = new RevokedStatus(caCompromisedStatus.CompromisedDate.Value.UtcDateTime, (int)RevocationReason.CACompromise);
                }
                else
                {
                    // Se section 2.2 of RFC 6960
                    if (await OcspResponderRepository.SerialExists(serialNumber, issuerCertificate))
                    {
                        var status = await OcspResponderRepository.SerialIsRevoked(serialNumber, issuerCertificate);

                        certificateStatus = status.IsRevoked
                            ? new RevokedStatus(status.RevokedInfo.Date.UtcDateTime, (int)status.RevokedInfo.Reason)
                            :  CertificateStatus.Good;
                    }
                    else
                    {
                        certificateStatus = new RevokedStatus(new DateTime(1970, 1, 1), CrlReason.CertificateHold);
                        extensionsGenerator.AddExtension(OcspObjectIdentifierExtensions.PkixOcspExtendedRevoke, false, DerNull.Instance.GetDerEncoded());
                    }
                }

                basicResponseGenerator.AddResponse(certificateId, certificateStatus, DateTimeOffset.UtcNow.DateTime, nextUpdate.UtcDateTime, null);
            }

            SetNonceExtension(ocspRequest, extensionsGenerator);

            basicResponseGenerator.SetResponseExtensions(extensionsGenerator.Generate());

            // Algorithm that all clients shall accept as defined in section 4.3 of RFC 6960
            const string signatureAlgorithm = "sha256WithRSAEncryption";
            var          basicOcspResponse  = basicResponseGenerator.Generate(
                signatureAlgorithm,
                await OcspResponderRepository.GetResponderPrivateKey(issuerCertificate),
                await OcspResponderRepository.GetChain(issuerCertificate),
                nextUpdate.UtcDateTime);

            var ocspResponse = OcspResponseGenerator.Generate(OcspRespStatus.Successful, basicOcspResponse);

            return(ocspResponse);
        }
Exemple #7
0
        private static void Verify(IReadOnlyList <TestExtension> testExtensions)
        {
            var bcExtensionsGenerator = new X509ExtensionsGenerator();

            foreach (var testExtension in testExtensions)
            {
                bcExtensionsGenerator.AddExtension(
                    new DerObjectIdentifier(testExtension.Id.Value), testExtension.IsCritical, testExtension.Value);
            }

            var bcExtensions = bcExtensionsGenerator.Generate();

            var extensions = Extensions.Read(bcExtensions.GetDerEncoded());

            Assert.Equal(testExtensions.Count, extensions.ExtensionsList.Count);

            var i = 0;

            foreach (var extensionOid in bcExtensions.GetExtensionOids())
            {
                var bcExtension   = bcExtensions.GetExtension(extensionOid);
                var testExtension = testExtensions[i];
                var extension     = extensions.ExtensionsList[i];

                Assert.Equal(testExtension.Id.Value, extension.Id.Value);
                Assert.Equal(testExtension.IsCritical, extension.Critical);
                Assert.Equal(testExtension.Value, extension.Value);

                Assert.Equal(extensionOid.Id, extension.Id.Value);
                Assert.Equal(bcExtension.IsCritical, extension.Critical);
                Assert.Equal(bcExtension.Value.GetOctets(), extension.Value);

                ++i;
            }
        }
Exemple #8
0
        /// <summary>
        /// Add nonce extension if it exists in the request
        /// </summary>
        /// <param name="ocspRequest">ocsp request</param>
        /// <param name="extensionsGenerator">extensions generator</param>
        private void SetNonceExtension(OcspReq ocspRequest, X509ExtensionsGenerator extensionsGenerator)
        {
            var nonce = ocspRequest.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce);

            if (nonce != null)
            {
                extensionsGenerator.AddExtension(OcspObjectIdentifiers.PkixOcspNonce, false, nonce.GetOctets());
            }
        }
Exemple #9
0
        public static void CreateCert(string parentcer, string csrFile)
        {
            var issuer = new X509CertificateParser().ReadCertificate(File.OpenRead(parentcer));

            var reader = new PemReader(File.OpenText(csrFile));

            var csr     = (Pkcs10CertificationRequest)(reader.ReadObject());
            var csrinfo = csr.GetCertificationRequestInfo();

            AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
            BigInteger          serial   = new BigInteger(128, new SecureRandom());
            DateTime            from     = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            DateTime to = from.AddYears(5);


            V3TbsCertificateGenerator tbsGen = new V3TbsCertificateGenerator();

            tbsGen.SetIssuer(issuer.SubjectDN);
            tbsGen.SetSerialNumber(new DerInteger(serial));
            tbsGen.SetStartDate(new Time(from));
            tbsGen.SetEndDate(new Time(to));
            tbsGen.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(csr.GetPublicKey()));
            tbsGen.SetSubject(csrinfo.Subject);

            // add certificate purposes
            Asn1EncodableVector vector = new Asn1EncodableVector();

            vector.Add(new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"));
            vector.Add(new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.2"));
            vector.Add(new DerObjectIdentifier("1.3.6.1.4.1.311.10.3.12"));
            vector.Add(new DerObjectIdentifier("1.3.6.1.5.5.7.3.4"));
            DerSequence             seq          = new DerSequence(vector);
            X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();

            extGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, seq);

            tbsGen.SetExtensions(extGenerator.Generate());

            tbsGen.SetSignature(sigAlgId);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            // save the TBS
            System.IO.File.WriteAllBytes("tbs.cer", tbsCert.GetDerEncoded());

            Console.WriteLine("generate the signature (SHA->DER->ENCRYPT) for tbs.cer and call it tbs.sig");
            Console.WriteLine("And then press enter");
            Console.ReadLine();

            var t1 = GenerateJcaObject(tbsCert, sigAlgId, System.IO.File.ReadAllBytes("tbs.sig").Take(256).ToArray());

            System.IO.File.WriteAllBytes("cert.cer", t1.GetEncoded());

            Console.WriteLine("saved as cert.cer");
        }
Exemple #10
0
        /// <summary>
        /// Get an X509Extensions object containing all extensions from the request
        /// </summary>
        /// <returns>List of extension (or null)</returns>
        private X509Extensions getExtensions()
        {
            if (Attributes == null)
            {
                return(null);
            }

            DerObjectIdentifier ExtensionsOid = new DerObjectIdentifier("1.2.840.113549.1.9.14");

            // Iterate over the Attributes
            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                // Find the Attribute entry that has extensions in it
                if (ExtensionsOid.Equals(attrib.AttrType))
                {
                    X509ExtensionsGenerator gen = new X509ExtensionsGenerator();
                    bool critical;
                    foreach (DerSequence outer in attrib.AttrValues)
                    {
                        foreach (DerSequence inner in outer)
                        {
                            // Note that the extension value is wrapped in an OctetString, but the generator expects an unwrapped value
                            if (inner.Count == 3)                        // Critical flag set
                            {
                                critical = isTrue((DerBoolean)inner[1]); // Just in case it is false
                                gen.AddExtension((DerObjectIdentifier)inner[0], critical, ((DerOctetString)inner[2]).GetOctets());
                            }
                            else                       // Count==2; Critical flag not set
                            {
                                gen.AddExtension((DerObjectIdentifier)inner[0], false, ((DerOctetString)inner[1]).GetOctets());
                            }
                        }
                    }
                    return(gen.Generate());
                }
            }
            return(null);
        }
Exemple #11
0
        MakePartialCert(X509KeyUsage keyUsage, AlgorithmIdentifier algID = null,
                        string issuer      = null, string subject    = null,
                        DateTime?notBefore = null, DateTime?notAfter = null)
        {
            X509ExtensionsGenerator g = new X509ExtensionsGenerator();

            g.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            return(new PartialCertificate()
            {
                Issuer = new X509Name(issuer ?? "CN=TPM Test Issuer,O=TPM Test Suite"),
                NotBefore = notBefore ?? new DateTime(2000, 1, 1),
                NotAfter = notAfter ?? new DateTime(2999, 12, 31),
                Subject = new X509Name(subject ?? "CN=TPM X509 CA,O=MSFT"),
                SigAlgID = algID,
                Extensions = g.Generate()
            });
        }
Exemple #12
0
        private static TbsCertificateStructure CreateTbsForVerification(X509Certificate2 preCertificate, IssuerInformation issuerInformation)
        {
            if (preCertificate.Version < 3)
            {
                throw new InvalidOperationException("PreCertificate version must be 3 or higher!");
            }

            var asn1Obj = Asn1Object.FromByteArray(preCertificate.GetTbsCertificateRaw());
            var tbsCert = TbsCertificateStructure.GetInstance(asn1Obj);
            var hasX509AuthorityKeyIdentifier = tbsCert.Extensions.GetExtension(new DerObjectIdentifier(Constants.X509AuthorityKeyIdentifier)) != null;

            if (hasX509AuthorityKeyIdentifier &&
                issuerInformation.IssuedByPreCertificateSigningCert &&
                issuerInformation.X509AuthorityKeyIdentifier == null)
            {
                throw new InvalidOperationException("PreCertificate was not signed by a PreCertificate signing cert");
            }

            var orderedExtensions = GetExtensionsWithoutPoisonAndSct(tbsCert.Extensions, issuerInformation.X509AuthorityKeyIdentifier);

            var generator = new V3TbsCertificateGenerator();

            generator.SetSerialNumber(tbsCert.SerialNumber);
            generator.SetSignature(tbsCert.Signature);
            generator.SetIssuer(issuerInformation.Name ?? tbsCert.Issuer);
            generator.SetStartDate(tbsCert.StartDate);
            generator.SetEndDate(tbsCert.EndDate);
            generator.SetSubject(tbsCert.Subject);
            generator.SetSubjectPublicKeyInfo(tbsCert.SubjectPublicKeyInfo);
            generator.SetIssuerUniqueID(tbsCert.IssuerUniqueID);
            generator.SetSubjectUniqueID(tbsCert.SubjectUniqueID);

            var extensionsGenerator = new X509ExtensionsGenerator();

            foreach (var e in orderedExtensions)
            {
                extensionsGenerator.AddExtension(e.Key, e.Value.IsCritical, e.Value.GetParsedValue());
            }

            generator.SetExtensions(extensionsGenerator.Generate());

            return(generator.GenerateTbsCertificate());
        }
Exemple #13
0
        /// <summary>
        /// Makes a minimal partial certificate for a signing key
        /// </summary>
        /// <returns></returns>
        internal static PartialCertificate MakeExemplarPartialCert()
        {
            X509ExtensionsGenerator g = new X509ExtensionsGenerator();

            g.AddExtension(X509Extensions.KeyUsage, true, new X509KeyUsage(X509KeyUsage.KeyCertSign));

            var tt = new X509KeyUsage(X509KeyUsage.KeyCertSign);
            var yy = tt.GetDerEncoded();

            return(new PartialCertificate()
            {
                Issuer = new X509Name("CN=TPM Test Issuer,O=TPM Test Suite"),
                NotBefore = new DateTime(2000, 1, 1),
                NotAfter = new DateTime(2999, 12, 31),
                Subject = new X509Name("CN=TPM X509 CA,O=MSFT"),
//                IssuerUniqueId = new byte[32],
//                SubjectUniqueId = new byte[32],
                Extensions = g.Generate()
            });
        }
        private void additionalExtensionTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);
            tsTokenGen.SetTsa(new Asn1.X509.GeneralName(new X509Name("CN=Test")));

            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            X509ExtensionsGenerator extensionsGenerator = new X509ExtensionsGenerator();

            extensionsGenerator.AddExtension(X509Extensions.AuditIdentity, false, new DerUtf8String("Test"));


            TimeStampResponse tsResp = tsRespGen.GenerateGrantedResponse(request, new BigInteger("23"), new DateTimeObject(DateTime.UtcNow), "Okay", extensionsGenerator.Generate());

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");

            X509Extensions ext = tsToken.TimeStampInfo.TstInfo.Extensions;

            Assert.True(1 == ext.GetExtensionOids().Length);

            X509Extension left = new X509Extension(DerBoolean.False, new DerOctetString(new DerUtf8String("Test").GetEncoded()));

            Assert.True(left.Equals(ext.GetExtension(X509Extensions.AuditIdentity)));
        }
Exemple #15
0
        public TimeStampToken Generate(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime genTime, X509Extensions additionalExtensions)
        {
            DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid);

            AlgorithmIdentifier algID          = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest());

            Accuracy accuracy = null;

            if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
            {
                DerInteger seconds = null;
                if (accuracySeconds > 0)
                {
                    seconds = new DerInteger(accuracySeconds);
                }

                DerInteger millis = null;
                if (accuracyMillis > 0)
                {
                    millis = new DerInteger(accuracyMillis);
                }

                DerInteger micros = null;
                if (accuracyMicros > 0)
                {
                    micros = new DerInteger(accuracyMicros);
                }

                accuracy = new Accuracy(seconds, millis, micros);
            }

            DerBoolean derOrdering = null;

            if (ordering)
            {
                derOrdering = DerBoolean.GetInstance(ordering);
            }

            DerInteger nonce = null;

            if (request.Nonce != null)
            {
                nonce = new DerInteger(request.Nonce);
            }

            DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID);

            if (request.ReqPolicy != null)
            {
                tsaPolicy = new DerObjectIdentifier(request.ReqPolicy);
            }


            X509Extensions respExtensions = request.Extensions;

            if (additionalExtensions != null)
            {
                X509ExtensionsGenerator extGen = new X509ExtensionsGenerator();

                if (respExtensions != null)
                {
                    foreach (object oid in respExtensions.ExtensionOids)
                    {
                        DerObjectIdentifier id = DerObjectIdentifier.GetInstance(oid);
                        extGen.AddExtension(id, respExtensions.GetExtension(DerObjectIdentifier.GetInstance(id)));
                    }
                }

                foreach (object oid in additionalExtensions.ExtensionOids)
                {
                    DerObjectIdentifier id = DerObjectIdentifier.GetInstance(oid);
                    extGen.AddExtension(id, additionalExtensions.GetExtension(DerObjectIdentifier.GetInstance(id)));
                }

                respExtensions = extGen.Generate();
            }



            DerGeneralizedTime generalizedTime;

            if (resolution != Resolution.R_SECONDS)
            {
                generalizedTime = new DerGeneralizedTime(createGeneralizedTime(genTime));
            }
            else
            {
                generalizedTime = new DerGeneralizedTime(genTime);
            }


            TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint,
                                          new DerInteger(serialNumber), generalizedTime, accuracy,
                                          derOrdering, nonce, tsa, respExtensions);

            try
            {
                CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();

                byte[] derEncodedTstInfo = tstInfo.GetDerEncoded();

                if (request.CertReq)
                {
                    signedDataGenerator.AddCertificates(x509Certs);
                }

                signedDataGenerator.AddCrls(x509Crls);

                signedDataGenerator.AddSignerInfoGenerator(signerInfoGenerator);

                CmsSignedData signedData = signedDataGenerator.Generate(
                    PkcsObjectIdentifiers.IdCTTstInfo.Id,
                    new CmsProcessableByteArray(derEncodedTstInfo),
                    true);

                return(new TimeStampToken(signedData));
            }
            catch (CmsException cmsEx)
            {
                throw new TspException("Error generating time-stamp token", cmsEx);
            }
            catch (IOException e)
            {
                throw new TspException("Exception encoding info", e);
            }
            catch (X509StoreException e)
            {
                throw new TspException("Exception handling CertStore", e);
            }
            //			catch (InvalidAlgorithmParameterException e)
            //			{
            //				throw new TspException("Exception handling CertStore CRLs", e);
            //			}
        }
Exemple #16
0
        /// <summary>
        /// Creates an ASN.1 DER-encoded PKCS#10 CertificationRequest object representing
        /// the current state of this CertificateRequest object.
        /// </summary>
        /// <returns>An ASN.1 DER-encoded certificate signing request.</returns>
        public byte[] ExportSigningRequest(PkiEncodingFormat format)
        {
            if (!HasPrivateKey)
            {
                throw new InvalidOperationException("cannot export CSR without a private key");
            }

            // Based on:
            //    https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/pkcs/test/PKCS10Test.cs
            //    https://stackoverflow.com/questions/46182659/how-to-delay-sign-the-certificate-request-using-bouncy-castle-with-ecdsa-signatu
            //    http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation:
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-EllipticCurve(ECDSA)
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-RSA
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-CreatingCertificationRequests
            //    https://stackoverflow.com/a/37563051/5428506

            var x509name = new X509Name(SubjectName);
            var pubKey   = _keyPair.PublicKey.NativeKey;
            var prvKey   = _keyPair.PrivateKey.NativeKey;

            // Asn1Set attrSet = null;
            // if (CertificateExtensions.Count > 0)
            // {
            //     var certExts = CertificateExtensions.ToDictionary(
            //             ext => ext.Identifier, ext => ext.Value);
            //     var csrAttrs = new[]
            //     {
            //         new Org.BouncyCastle.Asn1.Cms.Attribute(
            //             PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
            //             new DerSet(new X509Extensions(certExts))),
            //     };
            //     attrSet = new DerSet(csrAttrs);
            // }

            // Based on:
            //    http://forum.rebex.net/4284/pkcs10-certificate-request-example-provided-castle-working

            var extGen = new X509ExtensionsGenerator();

            foreach (var ext in CertificateExtensions)
            {
                extGen.AddExtension(ext.Identifier, ext.IsCritical, ext.Value);
            }
            var attr = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                         new DerSet(extGen.Generate()));

            var sigFactory = ComputeSignatureAlgorithm(prvKey);
            var pkcs10     = new Pkcs10CertificationRequest(sigFactory, x509name,
                                                            pubKey, new DerSet(attr), prvKey);

            switch (format)
            {
            case PkiEncodingFormat.Pem:
                using (var sw = new StringWriter())
                {
                    var pemWriter = new PemWriter(sw);
                    pemWriter.WriteObject(pkcs10);
                    return(Encoding.UTF8.GetBytes(sw.GetStringBuilder().ToString()));
                }

            case PkiEncodingFormat.Der:
                return(pkcs10.GetDerEncoded());

            default:
                throw new NotSupportedException();
            }
        }
        public override void PerformTest()
        {
            X509ExtensionsGenerator gen = new X509ExtensionsGenerator();

            gen.AddExtension(Oid1, true, new byte[20]);
            gen.AddExtension(Oid2, true, new byte[20]);

            X509Extensions ext1 = gen.Generate();
            X509Extensions ext2 = gen.Generate();

            if (!ext1.Equals(ext2))
            {
                Fail("Equals test failed");
            }

            gen.Reset();

            gen.AddExtension(Oid2, true, new byte[20]);
            gen.AddExtension(Oid1, true, new byte[20]);

            ext2 = gen.Generate();

            if (ext1.Equals(ext2))
            {
                Fail("inequality test failed");
            }

            if (!ext1.Equivalent(ext2))
            {
                Fail("equivalence true failed");
            }

            gen.Reset();

            gen.AddExtension(Oid1, true, new byte[22]);
            gen.AddExtension(Oid2, true, new byte[20]);

            ext2 = gen.Generate();

            if (ext1.Equals(ext2))
            {
                Fail("inequality 1 failed");
            }

            if (ext1.Equivalent(ext2))
            {
                Fail("non-equivalence 1 failed");
            }

            gen.Reset();

            gen.AddExtension(Oid3, true, new byte[20]);
            gen.AddExtension(Oid2, true, new byte[20]);

            ext2 = gen.Generate();

            if (ext1.Equals(ext2))
            {
                Fail("inequality 2 failed");
            }

            if (ext1.Equivalent(ext2))
            {
                Fail("non-equivalence 2 failed");
            }

            try
            {
                gen.AddExtension(Oid2, true, new byte[20]);
                Fail("repeated oid");
            }
            catch (ArgumentException e)
            {
                if (!e.Message.Equals("extension 1.2.2 already added"))
                {
                    Fail("wrong exception on repeated oid: " + e.Message);
                }
            }
        }
 public CertificateRequestMessageBuilder AddExtension(DerObjectIdentifier oid, bool critical,
                                                      Asn1Encodable value)
 {
     _extGenerator.AddExtension(oid, critical, value);
     return(this);
 }