private static void CheckCrl(DistributionPoint dp, IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, DateTime validDate, X509Certificate issuerCert, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts)
        {
            if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
            {
                return;
            }
            DateTime utcNow = DateTime.UtcNow;

            if (validDate.CompareTo(utcNow) > 0)
            {
                throw new Exception("Validation time is in future.");
            }
            ISet        completeCrls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert, utcNow, paramsPKIX);
            bool        flag         = false;
            Exception   ex           = null;
            IEnumerator enumerator   = completeCrls.GetEnumerator();

            while (enumerator.MoveNext() && certStatus.Status == 11 && !reasonMask.IsAllReasons)
            {
                try
                {
                    X509Crl     x509Crl     = (X509Crl)enumerator.Current;
                    ReasonsMask reasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(x509Crl, dp);
                    if (reasonsMask.HasNewReasons(reasonMask))
                    {
                        ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(x509Crl, attrCert, null, null, paramsPKIX, certPathCerts);
                        AsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(x509Crl, keys);
                        X509Crl x509Crl2           = null;
                        if (paramsPKIX.IsUseDeltasEnabled)
                        {
                            ISet deltaCrls = PkixCertPathValidatorUtilities.GetDeltaCrls(utcNow, paramsPKIX, x509Crl);
                            x509Crl2 = Rfc3280CertPathUtilities.ProcessCrlH(deltaCrls, key);
                        }
                        if (paramsPKIX.ValidityModel != 1 && attrCert.NotAfter.CompareTo(x509Crl.ThisUpdate) < 0)
                        {
                            throw new Exception("No valid CRL for current time found.");
                        }
                        Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, x509Crl);
                        Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, x509Crl);
                        Rfc3280CertPathUtilities.ProcessCrlC(x509Crl2, x509Crl, paramsPKIX);
                        Rfc3280CertPathUtilities.ProcessCrlI(validDate, x509Crl2, attrCert, certStatus, paramsPKIX);
                        Rfc3280CertPathUtilities.ProcessCrlJ(validDate, x509Crl, attrCert, certStatus);
                        if (certStatus.Status == 8)
                        {
                            certStatus.Status = 11;
                        }
                        reasonMask.AddReasons(reasonsMask);
                        flag = true;
                    }
                }
                catch (Exception ex2)
                {
                    ex = ex2;
                }
            }
            if (!flag)
            {
                throw ex;
            }
        }
Esempio n. 2
0
    protected void buttonAddDp_OnClick(object sender, EventArgs e)
    {
        RequiresAuthorization(Authorizations.UpdateAdmin);
        var distributionPoint = new DistributionPoint
        {
            DisplayName  = txtDisplayName.Text,
            Server       = txtServer.Text,
            Protocol     = ddlProtocol.Text,
            ShareName    = txtShareName.Text,
            Domain       = txtDomain.Text,
            RwUsername   = txtRwUsername.Text,
            RwPassword   = new Helpers.Encryption().EncryptText(txtRwPassword.Text),
            RoUsername   = txtRoUsername.Text,
            RoPassword   = new Helpers.Encryption().EncryptText(txtRoPassword.Text),
            IsPrimary    = Convert.ToInt16(chkPrimary.Checked),
            PhysicalPath = chkPrimary.Checked ? txtPhysicalPath.Text : "",
        };

        var result = BLL.DistributionPoint.AddDistributionPoint(distributionPoint);

        if (result.IsValid)
        {
            EndUserMessage = "Successfully Created Distribution Point";
            Response.Redirect("~/views/admin/dp/edit.aspx?level=2&dpid=" + distributionPoint.Id);
        }
        else
        {
            EndUserMessage = result.Message;
        }
    }
Esempio n. 3
0
        internal static CertContainer IssueSignerCertificate(X509Name dnName, int keySize = DefaultKeySize)
        {
            CertContainer issuerCert = IntermediateCa;

            RsaKeyPairGenerator keyPairGen = new RsaKeyPairGenerator();

            keyPairGen.Init(new KeyGenerationParameters(_secureRandom, keySize));
            AsymmetricCipherKeyPair keyPair = keyPairGen.GenerateKeyPair();

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(issuerCert.Certificate.SubjectDN);
            certGen.SetNotBefore(DateTime.Now);
            certGen.SetNotAfter(DateTime.Now.AddYears(1));

            certGen.SetSubjectDN(dnName);
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm("SHA256withRSA");
            certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert.Certificate.GetPublicKey()));
            certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.NonRepudiation | X509KeyUsage.DigitalSignature));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));
            certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth));

            // Add CRL endpoint
            Uri currentBaseUri = new Uri("https://localhost/");
            Uri crlUri         = new Uri(currentBaseUri, IntermediateCrlPath);

            GeneralName           generalName   = new GeneralName(GeneralName.UniformResourceIdentifier, crlUri.ToString());
            GeneralNames          generalNames  = new GeneralNames(generalName);
            DistributionPointName distPointName = new DistributionPointName(generalNames);
            DistributionPoint     distPoint     = new DistributionPoint(distPointName, null, null);

            certGen.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(new DistributionPoint[] { distPoint }));

            // Add OCSP endpoint
            Uri ocspUri            = new Uri(currentBaseUri, OcspPath);
            AccessDescription ocsp = new AccessDescription(AccessDescription.IdADOcsp,
                                                           new GeneralName(GeneralName.UniformResourceIdentifier, ocspUri.ToString()));

            Asn1EncodableVector aiaASN = new Asn1EncodableVector();

            aiaASN.Add(ocsp);

            certGen.AddExtension(X509Extensions.AuthorityInfoAccess, false, new DerSequence(aiaASN));

            X509Certificate generatedCert = certGen.Generate(issuerCert.PrivateKey);

            Pkcs12StoreBuilder pfxBuilder = new Pkcs12StoreBuilder();
            Pkcs12Store        pfxStore   = pfxBuilder.Build();

            X509CertificateEntry certEntry = new X509CertificateEntry(generatedCert);

            pfxStore.SetCertificateEntry(generatedCert.SubjectDN.ToString(), certEntry);
            pfxStore.SetKeyEntry(generatedCert.SubjectDN + "_key", new AsymmetricKeyEntry(keyPair.Private), new X509CertificateEntry[] { certEntry });

            return(new CertContainer(pfxStore, issuerCert.GetIssuerChain(true)));
        }
        private static CrlDistPoint CreateCrlDistributionPoint(string uri)
        {
            var gn = new GeneralName(GeneralName.UniformResourceIdentifier, uri);
            var distributionPointname = new DistributionPointName(DistributionPointName.FullName, gn);
            var distributionPoint     = new DistributionPoint(distributionPointname, null, null);

            return(new CrlDistPoint(new[] { distributionPoint }));
        }
 public DistributionPoint[] GetDistributionPoints()
 {
     DistributionPoint[] array = new DistributionPoint[seq.Count];
     for (int i = 0; i != seq.Count; i++)
     {
         array[i] = DistributionPoint.GetInstance(seq[i]);
     }
     return(array);
 }
        /**
         * Fetches complete CRLs according to RFC 3280.
         *
         * @param dp The distribution point for which the complete CRL
         * @param cert The <code>X509Certificate</code> or
         *            {@link Essensoft.AspNetCore.Security.x509.X509AttributeCertificate} for
         *            which the CRL should be searched.
         * @param currentDate The date for which the delta CRLs must be valid.
         * @param paramsPKIX The extended PKIX parameters.
         * @return A <code>Set</code> of <code>X509CRL</code>s with complete
         *         CRLs.
         * @throws Exception if an exception occurs while picking the CRLs
         *             or no CRLs are found.
         */
        internal static ISet GetCompleteCrls(
            DistributionPoint dp,
            object cert,
            DateTime currentDate,
            PkixParameters paramsPKIX)
        {
            X509CrlStoreSelector crlselect = new X509CrlStoreSelector();

            try
            {
                ISet issuers = new HashSet();
                if (cert is X509V2AttributeCertificate)
                {
                    issuers.Add(((X509V2AttributeCertificate)cert)
                                .Issuer.GetPrincipals()[0]);
                }
                else
                {
                    issuers.Add(GetIssuerPrincipal(cert));
                }
                PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
            }
            catch (Exception e)
            {
                throw new Exception("Could not get issuer information from distribution point.", e);
            }

            if (cert is X509Certificate)
            {
                crlselect.CertificateChecking = (X509Certificate)cert;
            }
            else if (cert is X509V2AttributeCertificate)
            {
                crlselect.AttrCertChecking = (IX509AttributeCertificate)cert;
            }

            crlselect.CompleteCrlEnabled = true;
            ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);

            if (crls.IsEmpty)
            {
                if (cert is IX509AttributeCertificate)
                {
                    IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert;

                    throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\"");
                }
                else
                {
                    X509Certificate xCert = (X509Certificate)cert;

                    throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\"");
                }
            }

            return(crls);
        }
Esempio n. 7
0
        /// <summary>
        /// Return the distribution points making up the sequence.
        /// </summary>
        /// <returns>DistributionPoint[]</returns>
        public DistributionPoint[] GetDistributionPoints()
        {
            DistributionPoint[] dp = new DistributionPoint[seq.Count];

            for (int i = 0; i != seq.Count; ++i)
            {
                dp[i] = DistributionPoint.GetInstance(seq[i]);
            }

            return(dp);
        }
Esempio n. 8
0
        public void CalcPoint_OrderEqualTotalNotDark_Test()
        {
            var target = new DistributionPoint(5);

            target.Order  = 5;
            target.Count  = 5;
            target.IsDark = false;
            var expected = 500;
            var actual   = target.CalcPoint();

            Assert.AreEqual(expected, actual);
        }
Esempio n. 9
0
        public void CalcPoint_OrderTotalWithDark_Test()
        {
            var target = new DistributionPoint(9);

            target.Order  = 9;
            target.Count  = 9;
            target.IsDark = true;
            var expected = 1800;
            var actual   = target.CalcPoint();

            Assert.AreEqual(expected, actual);
        }
Esempio n. 10
0
        public void CalcPoint_OrderEqualCountAndDark_Test()
        {
            var target = new DistributionPoint(9);

            target.Order  = 1;
            target.Count  = 1;
            target.IsDark = true;
            var expected = 200;
            var actual   = target.CalcPoint();

            Assert.AreEqual(expected, actual);
        }
Esempio n. 11
0
        public void CalcPoint_Pass_Test()
        {
            var target = new DistributionPoint(1);

            target.Order  = 0;
            target.Count  = 0;
            target.IsDark = false;
            var expected = 50;
            var actual   = target.CalcPoint();

            Assert.AreEqual(expected, actual);
        }
Esempio n. 12
0
        public void ShuffleListOfOneItem()
        {
            var p      = new DistributionPoint(1, 1);
            var points = new List <DistributionPoint> {
                p
            };

            points.Shuffle();

            Assert.Single(points);
            Assert.Contains(p, points);
        }
Esempio n. 13
0
        public void CalcPoint_OrderLessCountAndNotDark_Test()
        {
            var target = new DistributionPoint(2);

            target.Order  = 1;
            target.Count  = 0;
            target.IsDark = false;
            var expected = -100;
            var actual   = target.CalcPoint();

            Assert.AreEqual(expected, actual);
        }
        public DistributionPoint GetDistributionPoint()
        {
            if (lastDistributionPoint >= distribution.Count)
            {
                return(new DistributionPoint());
            }

            DistributionPoint point = distribution[lastDistributionPoint];

            lastDistributionPoint = (lastDistributionPoint + 1) % distribution.Count;

            return(point);
        }
Esempio n. 15
0
        /// <summary>
        /// Create a Distribution Point list
        /// </summary>
        /// <returns>Distribution Point list</returns>
        protected virtual DistributionPoint[] encode()
        {
            DistributionPoint[] dplist = new DistributionPoint[distPoints.Count()];
            int i = 0;

            foreach (OSCAGeneralName cdp in distPoints)
            {
                GeneralNames          gn  = generalNames.createGeneralNames(cdp.Type.ToString(), cdp.Name);
                DistributionPointName dpn = new DistributionPointName(gn);
                DistributionPoint     dp  = new DistributionPoint(dpn, null, null);
                dplist[i] = dp;
                i++;
            }
            return(dplist);
        }
Esempio n. 16
0
        /// <summary>
        /// Attaches multiple distribution points to the certificate currently in the chain.
        /// </summary>
        /// <param name="urls">A list of http CRL locations</param>
        /// <returns></returns>
        public CertificateBuilder AddCRLDistributionPoints(string[] urls)
        {
            var dps = new DistributionPoint[urls.Length];

            for (int i = 0; i < urls.Length; i++)
            {
                string url    = urls[i];
                var    name   = new GeneralName(GeneralName.UniformResourceIdentifier, url.Trim());
                var    dpName = new DistributionPointName(DistributionPointName.FullName, name);
                dps[i] = new DistributionPoint(dpName, null, null);
                logger.Debug($"[ADD DISTRIBUTION POINT] => {url}");
            }

            certificateGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, new CrlDistPoint(dps));
            return(this);
        }
Esempio n. 17
0
        public void AddCrlDistributionPoints()
        {
            var distributionPoints = new List <Asn1Encodable>();

            foreach (var endpoint in CrlEndpoints)
            {
                var generalName = new GeneralName(GeneralName.UniformResourceIdentifier, new DerIA5String(endpoint));
                var gns         = new GeneralNames(generalName);
                var dpn         = new DistributionPointName(gns);
                var distp       = new DistributionPoint(dpn, null, null);
                distributionPoints.Add(distp);
            }

            var seq = new DerSequence(distributionPoints.ToArray());

            certificateGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, seq);
        }
Esempio n. 18
0
        internal static ISet GetCompleteCrls(DistributionPoint dp, object cert, DateTime currentDate, PkixParameters paramsPKIX)
        {
            X509CrlStoreSelector x509CrlStoreSelector = new X509CrlStoreSelector();

            try
            {
                ISet set = new HashSet();
                if (cert is X509V2AttributeCertificate)
                {
                    set.Add(((X509V2AttributeCertificate)cert).Issuer.GetPrincipals()[0]);
                }
                else
                {
                    set.Add(PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert));
                }
                PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, set, x509CrlStoreSelector, paramsPKIX);
            }
            catch (Exception innerException)
            {
                throw new Exception("Could not get issuer information from distribution point.", innerException);
            }
            if (cert is X509Certificate)
            {
                x509CrlStoreSelector.CertificateChecking = (X509Certificate)cert;
            }
            else if (cert is X509V2AttributeCertificate)
            {
                x509CrlStoreSelector.AttrCertChecking = (IX509AttributeCertificate)cert;
            }
            x509CrlStoreSelector.CompleteCrlEnabled = true;
            ISet set2 = PkixCertPathValidatorUtilities.CrlUtilities.FindCrls(x509CrlStoreSelector, paramsPKIX, currentDate);

            if (!set2.IsEmpty)
            {
                return(set2);
            }
            if (cert is IX509AttributeCertificate)
            {
                IX509AttributeCertificate iX509AttributeCertificate = (IX509AttributeCertificate)cert;
                throw new Exception("No CRLs found for issuer \"" + iX509AttributeCertificate.Issuer.GetPrincipals()[0] + "\"");
            }
            X509Certificate x509Certificate = (X509Certificate)cert;

            throw new Exception("No CRLs found for issuer \"" + x509Certificate.IssuerDN + "\"");
        }
Esempio n. 19
0
        internal static ISet GetCompleteCrls(DistributionPoint dp, object cert, global::System.DateTime currentDate, PkixParameters paramsPKIX)
        {
            X509CrlStoreSelector x509CrlStoreSelector = new X509CrlStoreSelector();

            try
            {
                ISet set = new HashSet();
                if (cert is X509V2AttributeCertificate)
                {
                    set.Add(((X509V2AttributeCertificate)cert).Issuer.GetPrincipals()[0]);
                }
                else
                {
                    set.Add(GetIssuerPrincipal(cert));
                }
                GetCrlIssuersFromDistributionPoint(dp, set, x509CrlStoreSelector, paramsPKIX);
            }
            catch (global::System.Exception ex)
            {
                throw new global::System.Exception("Could not get issuer information from distribution point.", ex);
            }
            if (cert is X509Certificate)
            {
                x509CrlStoreSelector.CertificateChecking = (X509Certificate)cert;
            }
            else if (cert is X509V2AttributeCertificate)
            {
                x509CrlStoreSelector.AttrCertChecking = (IX509AttributeCertificate)cert;
            }
            x509CrlStoreSelector.CompleteCrlEnabled = true;
            ISet set2 = CrlUtilities.FindCrls(x509CrlStoreSelector, paramsPKIX, currentDate);

            if (set2.IsEmpty)
            {
                if (cert is IX509AttributeCertificate)
                {
                    IX509AttributeCertificate iX509AttributeCertificate = (IX509AttributeCertificate)cert;
                    throw new global::System.Exception(string.Concat((object)"No CRLs found for issuer \"", (object)iX509AttributeCertificate.Issuer.GetPrincipals()[0], (object)"\""));
                }
                X509Certificate x509Certificate = (X509Certificate)cert;
                throw new global::System.Exception(string.Concat((object)"No CRLs found for issuer \"", (object)x509Certificate.IssuerDN, (object)"\""));
            }
            return(set2);
        }
Esempio n. 20
0
 internal static void GetCrlIssuersFromDistributionPoint(DistributionPoint dp, global::System.Collections.ICollection issuerPrincipals, X509CrlStoreSelector selector, PkixParameters pkixParams)
 {
     //IL_0045: Expected O, but got Unknown
     global::System.Collections.IList list = Platform.CreateArrayList();
     if (dp.CrlIssuer != null)
     {
         GeneralName[] names = dp.CrlIssuer.GetNames();
         for (int i = 0; i < names.Length; i++)
         {
             if (names[i].TagNo == 4)
             {
                 try
                 {
                     list.Add((object)X509Name.GetInstance(names[i].Name.ToAsn1Object()));
                 }
                 catch (IOException val)
                 {
                     IOException val2 = val;
                     throw new global::System.Exception("CRL issuer information from distribution point cannot be decoded.", (global::System.Exception)(object) val2);
                 }
             }
         }
     }
     else
     {
         if (dp.DistributionPointName == null)
         {
             throw new global::System.Exception("CRL issuer is omitted from distribution point but no distributionPoint field present.");
         }
         global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)issuerPrincipals).GetEnumerator();
         while (enumerator.MoveNext())
         {
             list.Add((object)(X509Name)enumerator.get_Current());
         }
     }
     selector.Issuers = (global::System.Collections.ICollection)list;
 }
Esempio n. 21
0
        internal static void GetCrlIssuersFromDistributionPoint(DistributionPoint dp, ICollection issuerPrincipals, X509CrlStoreSelector selector, PkixParameters pkixParams)
        {
            IList list = Platform.CreateArrayList();

            if (dp.CrlIssuer != null)
            {
                GeneralName[] names = dp.CrlIssuer.GetNames();
                for (int i = 0; i < names.Length; i++)
                {
                    if (names[i].TagNo == 4)
                    {
                        try
                        {
                            list.Add(X509Name.GetInstance(names[i].Name.ToAsn1Object()));
                        }
                        catch (IOException innerException)
                        {
                            throw new Exception("CRL issuer information from distribution point cannot be decoded.", innerException);
                        }
                    }
                }
            }
            else
            {
                if (dp.DistributionPointName == null)
                {
                    throw new Exception("CRL issuer is omitted from distribution point but no distributionPoint field present.");
                }
                IEnumerator enumerator = issuerPrincipals.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    list.Add((X509Name)enumerator.Current);
                }
            }
            selector.Issuers = list;
        }
Esempio n. 22
0
        protected void ApplyCrlExtension(
            X509V3CertificateGenerator certGen,
            string crlLink
            )
        {
            if (string.IsNullOrEmpty(crlLink))
            {
                return;
            }

            var distPointOne =
                new DistributionPointName(
                    new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, crlLink)));

            var distPoints = new DistributionPoint[1];

            distPoints[0] = new DistributionPoint(distPointOne, null, null);

            certGen.AddExtension(
                X509Extensions.CrlDistributionPoints,
                false,
                new CrlDistPoint(distPoints)
                );
        }
Esempio n. 23
0
        private static X509Certificate2 GenerateCertificate(
            string subjectName,
            Action <TestCertificateGenerator> modifyGenerator,
            RSA rsa,
            NuGet.Common.HashAlgorithmName hashAlgorithm,
            RSASignaturePaddingMode paddingMode,
            ChainCertificateRequest chainCertificateRequest)
        {
            if (string.IsNullOrEmpty(subjectName))
            {
                subjectName = "NuGetTest";
            }

            // Create cert
            var subjectDN = $"CN={subjectName}";
            var certGen   = new TestCertificateGenerator();

            var isSelfSigned          = true;
            X509Certificate2 issuer   = null;
            DateTimeOffset?  notAfter = null;

            var keyUsage = X509KeyUsageFlags.DigitalSignature;

            if (chainCertificateRequest == null)
            {
                // Self-signed certificates should have this flag set.
                keyUsage |= X509KeyUsageFlags.KeyCertSign;
            }
            else
            {
                if (chainCertificateRequest.Issuer != null)
                {
                    isSelfSigned = false;
                    // for a certificate with an issuer assign Authority Key Identifier
                    issuer = chainCertificateRequest?.Issuer;

                    notAfter = issuer.NotAfter.Subtract(TimeSpan.FromMinutes(5));
                    var publicKey = DotNetUtilities.GetRsaPublicKey(issuer.GetRSAPublicKey());

                    certGen.Extensions.Add(
                        new X509Extension(
                            Oids.AuthorityKeyIdentifier,
                            new AuthorityKeyIdentifierStructure(publicKey).GetEncoded(),
                            critical: false));
                }

                if (chainCertificateRequest.ConfigureCrl)
                {
                    // for a certificate in a chain create CRL distribution point extension
                    var issuerDN      = chainCertificateRequest?.Issuer?.Subject ?? subjectDN;
                    var crlServerUri  = $"{chainCertificateRequest.CrlServerBaseUri}{issuerDN}.crl";
                    var generalName   = new Org.BouncyCastle.Asn1.X509.GeneralName(Org.BouncyCastle.Asn1.X509.GeneralName.UniformResourceIdentifier, new DerIA5String(crlServerUri));
                    var distPointName = new DistributionPointName(new GeneralNames(generalName));
                    var distPoint     = new DistributionPoint(distPointName, null, null);

                    certGen.Extensions.Add(
                        new X509Extension(
                            TestOids.CrlDistributionPoints,
                            new DerSequence(distPoint).GetDerEncoded(),
                            critical: false));
                }

                if (chainCertificateRequest.IsCA)
                {
                    // update key usage with CA cert sign and crl sign attributes
                    keyUsage |= X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.KeyCertSign;
                }
            }

            var  padding = paddingMode.ToPadding();
            var  request = new CertificateRequest(subjectDN, rsa, hashAlgorithm.ConvertToSystemSecurityHashAlgorithmName(), padding);
            bool isCa    = isSelfSigned ? true : (chainCertificateRequest?.IsCA ?? false);

            certGen.NotAfter  = notAfter ?? DateTime.UtcNow.Add(TimeSpan.FromMinutes(30));
            certGen.NotBefore = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(30));

            var random       = new Random();
            var serial       = random.Next();
            var serialNumber = BitConverter.GetBytes(serial);

            Array.Reverse(serialNumber);
            certGen.SetSerialNumber(serialNumber);

            certGen.Extensions.Add(
                new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false));
            certGen.Extensions.Add(
                new X509KeyUsageExtension(keyUsage, critical: false));
            certGen.Extensions.Add(
                new X509BasicConstraintsExtension(certificateAuthority: isCa, hasPathLengthConstraint: false, pathLengthConstraint: 0, critical: true));

            // Allow changes
            modifyGenerator?.Invoke(certGen);

            foreach (var extension in certGen.Extensions)
            {
                request.CertificateExtensions.Add(extension);
            }

            X509Certificate2 certResult;

            if (isSelfSigned)
            {
                certResult = request.CreateSelfSigned(certGen.NotBefore, certGen.NotAfter);
            }
            else
            {
                using (var temp = request.Create(issuer, certGen.NotBefore, certGen.NotAfter, certGen.SerialNumber))
                {
                    certResult = temp.CopyWithPrivateKey(rsa);
                }
            }

            return(new X509Certificate2(certResult.Export(X509ContentType.Pkcs12), password: (string)null, keyStorageFlags: X509KeyStorageFlags.Exportable));
        }
Esempio n. 24
0
        /**
         * Checks if an attribute certificate is revoked.
         *
         * @param attrCert Attribute certificate to check if it is revoked.
         * @param paramsPKIX PKIX parameters.
         * @param issuerCert The issuer certificate of the attribute certificate
         *            <code>attrCert</code>.
         * @param validDate The date when the certificate revocation status should
         *            be checked.
         * @param certPathCerts The certificates of the certification path to be
         *            checked.
         *
         * @throws CertPathValidatorException if the certificate is revoked or the
         *             status cannot be checked or some error occurs.
         */
        internal static void CheckCrls(
            IX509AttributeCertificate attrCert,
            PkixParameters paramsPKIX,
            X509Certificate issuerCert,
            DateTime validDate,
            IList certPathCerts)
        {
            if (!paramsPKIX.IsRevocationEnabled)
            {
                return;
            }

            // check if revocation is available
            if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
            {
                if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null ||
                    attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
                {
                    throw new PkixCertPathValidatorException(
                              "No rev avail extension is set, but also an AC revocation pointer.");
                }

                return;
            }

            CrlDistPoint crldp = null;

            try
            {
                crldp = CrlDistPoint.GetInstance(
                    PkixCertPathValidatorUtilities.GetExtensionValue(
                        attrCert, X509Extensions.CrlDistributionPoints));
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(
                          "CRL distribution point extension could not be read.", e);
            }
            try
            {
                PkixCertPathValidatorUtilities
                .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(
                          "No additional CRL locations could be decoded from CRL distribution point extension.", e);
            }

            CertStatus  certStatus  = new CertStatus();
            ReasonsMask reasonsMask = new ReasonsMask();

            Exception lastException = null;
            bool      validCrlFound = false;

            // for each distribution point
            if (crldp != null)
            {
                DistributionPoint[] dps = null;
                try
                {
                    dps = crldp.GetDistributionPoints();
                }
                catch (Exception e)
                {
                    throw new PkixCertPathValidatorException(
                              "Distribution points could not be read.", e);
                }
                try
                {
                    for (int i = 0; i < dps.Length &&
                         certStatus.Status == CertStatus.Unrevoked &&
                         !reasonsMask.IsAllReasons; i++)
                    {
                        PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX
                                                         .Clone();
                        CheckCrl(dps[i], attrCert, paramsPKIXClone,
                                 validDate, issuerCert, certStatus, reasonsMask,
                                 certPathCerts);
                        validCrlFound = true;
                    }
                }
                catch (Exception e)
                {
                    lastException = new Exception(
                        "No valid CRL for distribution point found.", e);
                }
            }

            /*
             * If the revocation status has not been determined, repeat the
             * process above with any available CRLs not specified in a
             * distribution point but issued by the certificate issuer.
             */

            if (certStatus.Status == CertStatus.Unrevoked &&
                !reasonsMask.IsAllReasons)
            {
                try
                {
                    /*
                     * assume a DP with both the reasons and the cRLIssuer
                     * fields omitted and a distribution point name of the
                     * certificate issuer.
                     */
                    X509Name issuer;
                    try
                    {
                        issuer = X509Name.GetInstance(attrCert.Issuer.GetPrincipals()[0].GetEncoded());
                    }
                    catch (Exception e)
                    {
                        throw new Exception(
                                  "Issuer from certificate for CRL could not be reencoded.",
                                  e);
                    }
                    DistributionPoint dp = new DistributionPoint(
                        new DistributionPointName(0, new GeneralNames(
                                                      new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
                    PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
                    CheckCrl(dp, attrCert, paramsPKIXClone, validDate,
                             issuerCert, certStatus, reasonsMask, certPathCerts);
                    validCrlFound = true;
                }
                catch (Exception e)
                {
                    lastException = new Exception(
                        "No valid CRL for distribution point found.", e);
                }
            }

            if (!validCrlFound)
            {
                throw new PkixCertPathValidatorException(
                          "No valid CRL found.", lastException);
            }
            if (certStatus.Status != CertStatus.Unrevoked)
            {
                // This format is enforced by the NistCertPath tests
                string formattedDate = certStatus.RevocationDate.Value.ToString(
                    "ddd MMM dd HH:mm:ss K yyyy");
                string message = "Attribute certificate revocation after "
                                 + formattedDate;
                message += ", reason: "
                           + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
                throw new PkixCertPathValidatorException(message);
            }
            if (!reasonsMask.IsAllReasons &&
                certStatus.Status == CertStatus.Unrevoked)
            {
                certStatus.Status = CertStatus.Undetermined;
            }
            if (certStatus.Status == CertStatus.Undetermined)
            {
                throw new PkixCertPathValidatorException(
                          "Attribute certificate status could not be determined.");
            }
        }
Esempio n. 25
0
        /**
         *
         * Checks a distribution point for revocation information for the
         * certificate <code>attrCert</code>.
         *
         * @param dp The distribution point to consider.
         * @param attrCert The attribute certificate which should be checked.
         * @param paramsPKIX PKIX parameters.
         * @param validDate The date when the certificate revocation status should
         *            be checked.
         * @param issuerCert Certificate to check if it is revoked.
         * @param reasonMask The reasons mask which is already checked.
         * @param certPathCerts The certificates of the certification path to be
         *            checked.
         * @throws Exception if the certificate is revoked or the status
         *             cannot be checked or some error occurs.
         */
        private static void CheckCrl(
            DistributionPoint dp,
            IX509AttributeCertificate attrCert,
            PkixParameters paramsPKIX,
            DateTime validDate,
            X509Certificate issuerCert,
            CertStatus certStatus,
            ReasonsMask reasonMask,
            IList certPathCerts)
        {
            /*
             * 4.3.6 No Revocation Available
             *
             * The noRevAvail extension, defined in [X.509-2000], allows an AC
             * issuer to indicate that no revocation information will be made
             * available for this AC.
             */
            if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
            {
                return;
            }

            DateTime currentDate = DateTime.UtcNow;

            if (validDate.CompareTo(currentDate) > 0)
            {
                throw new Exception("Validation time is in future.");
            }

            // (a)

            /*
             * We always get timely valid CRLs, so there is no step (a) (1).
             * "locally cached" CRLs are assumed to be in getStore(), additional
             * CRLs must be enabled in the ExtendedPkixParameters and are in
             * getAdditionalStore()
             */
            ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert,
                                                                       currentDate, paramsPKIX);
            bool      validCrlFound = false;
            Exception lastException = null;

            IEnumerator crl_iter = crls.GetEnumerator();

            while (crl_iter.MoveNext() &&
                   certStatus.Status == CertStatus.Unrevoked &&
                   !reasonMask.IsAllReasons)
            {
                try
                {
                    X509Crl crl = (X509Crl)crl_iter.Current;

                    // (d)
                    ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp);

                    // (e)

                    /*
                     * The reasons mask is updated at the end, so only valid CRLs
                     * can update it. If this CRL does not contain new reasons it
                     * must be ignored.
                     */
                    if (!interimReasonsMask.HasNewReasons(reasonMask))
                    {
                        continue;
                    }

                    // (f)
                    ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert,
                                                                     null, null, paramsPKIX, certPathCerts);
                    // (g)
                    AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys);

                    X509Crl deltaCRL = null;

                    if (paramsPKIX.IsUseDeltasEnabled)
                    {
                        // get delta CRLs
                        ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(
                            currentDate, paramsPKIX, crl);
                        // we only want one valid delta CRL
                        // (h)
                        deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey);
                    }

                    /*
                     * CRL must be be valid at the current time, not the validation
                     * time. If a certificate is revoked with reason keyCompromise,
                     * cACompromise, it can be used for forgery, also for the past.
                     * This reason may not be contained in older CRLs.
                     */

                    /*
                     * in the chain model signatures stay valid also after the
                     * certificate has been expired, so they do not have to be in
                     * the CRL vality time
                     */
                    if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
                    {
                        /*
                         * if a certificate has expired, but was revoked, it is not
                         * more in the CRL, so it would be regarded as valid if the
                         * first check is not done
                         */
                        if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0)
                        {
                            throw new Exception(
                                      "No valid CRL for current time found.");
                        }
                    }

                    Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl);

                    // (b) (2)
                    Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl);

                    // (c)
                    Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX);

                    // (i)
                    Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL,
                                                         attrCert, certStatus, paramsPKIX);

                    // (j)
                    Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert,
                                                         certStatus);

                    // (k)
                    if (certStatus.Status == CrlReason.RemoveFromCrl)
                    {
                        certStatus.Status = CertStatus.Unrevoked;
                    }

                    // update reasons mask
                    reasonMask.AddReasons(interimReasonsMask);
                    validCrlFound = true;
                }
                catch (Exception e)
                {
                    lastException = e;
                }
            }
            if (!validCrlFound)
            {
                throw lastException;
            }
        }
        /**
         * Add the CRL issuers from the cRLIssuer field of the distribution point or
         * from the certificate if not given to the issuer criterion of the
         * <code>selector</code>.
         * <p>
         * The <code>issuerPrincipals</code> are a collection with a single
         * <code>X500Principal</code> for <code>X509Certificate</code>s. For
         * {@link X509AttributeCertificate}s the issuer may contain more than one
         * <code>X500Principal</code>.
         * </p>
         *
         * @param dp The distribution point.
         * @param issuerPrincipals The issuers of the certificate or attribute
         *            certificate which contains the distribution point.
         * @param selector The CRL selector.
         * @param pkixParams The PKIX parameters containing the cert stores.
         * @throws Exception if an exception occurs while processing.
         * @throws ClassCastException if <code>issuerPrincipals</code> does not
         * contain only <code>X500Principal</code>s.
         */
        internal static void GetCrlIssuersFromDistributionPoint(
            DistributionPoint dp,
            ICollection issuerPrincipals,
            X509CrlStoreSelector selector,
            PkixParameters pkixParams)
        {
            IList issuers = Platform.CreateArrayList();

            // indirect CRL
            if (dp.CrlIssuer != null)
            {
                GeneralName[] genNames = dp.CrlIssuer.GetNames();
                // look for a DN
                for (int j = 0; j < genNames.Length; j++)
                {
                    if (genNames[j].TagNo == GeneralName.DirectoryName)
                    {
                        try
                        {
                            issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
                        }
                        catch (IOException e)
                        {
                            throw new Exception(
                                      "CRL issuer information from distribution point cannot be decoded.",
                                      e);
                        }
                    }
                }
            }
            else
            {
                /*
                 * certificate issuer is CRL issuer, distributionPoint field MUST be
                 * present.
                 */
                if (dp.DistributionPointName == null)
                {
                    throw new Exception(
                              "CRL issuer is omitted from distribution point but no distributionPoint field present.");
                }

                // add and check issuer principals
                for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext();)
                {
                    issuers.Add((X509Name)it.Current);
                }
            }
            // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
            // distributionPoint
            //        if (dp.getDistributionPoint() != null)
            //        {
            //            // look for nameRelativeToCRLIssuer
            //            if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
            //            {
            //                // append fragment to issuer, only one
            //                // issuer can be there, if this is given
            //                if (issuers.size() != 1)
            //                {
            //                    throw new AnnotatedException(
            //                        "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
            //                }
            //                DEREncodable relName = dp.getDistributionPoint().getName();
            //                Iterator it = issuers.iterator();
            //                List issuersTemp = new ArrayList(issuers.size());
            //                while (it.hasNext())
            //                {
            //                    Enumeration e = null;
            //                    try
            //                    {
            //                        e = ASN1Sequence.getInstance(
            //                            new ASN1InputStream(((X500Principal) it.next())
            //                                .getEncoded()).readObject()).getObjects();
            //                    }
            //                    catch (IOException ex)
            //                    {
            //                        throw new AnnotatedException(
            //                            "Cannot decode CRL issuer information.", ex);
            //                    }
            //                    ASN1EncodableVector v = new ASN1EncodableVector();
            //                    while (e.hasMoreElements())
            //                    {
            //                        v.add((DEREncodable) e.nextElement());
            //                    }
            //                    v.add(relName);
            //                    issuersTemp.add(new X500Principal(new DERSequence(v)
            //                        .getDEREncoded()));
            //                }
            //                issuers.clear();
            //                issuers.addAll(issuersTemp);
            //            }
            //        }

            selector.Issuers = issuers;
        }
 public DistributionPoint Create(DistributionPoint distributionPoint)
 {
     _unitOfWork.DistributionPointRepository.Insert(distributionPoint);
     _unitOfWork.Save();
     return(distributionPoint);
 }
 public void Delete(DistributionPoint distributionPoint)
 {
     _unitOfWork.DistributionPointRepository.Delete(distributionPoint);
     _unitOfWork.Save();
 }
 public DistributionPoint Update(DistributionPoint distributionPoint)
 {
     _unitOfWork.DistributionPointRepository.Update(distributionPoint);
     _unitOfWork.Save();
     return(distributionPoint);
 }
Esempio n. 30
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            s_certGenerator.Reset();
            s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            // Tag on the generation time to prevent caching of the cert CRL in Linux
            X509Name authorityX509Name = CreateX509Name(string.Format("{0} {1}", _authorityCanonicalName, DateTime.Now.ToString("s")));
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                s_certGenerator.SetIssuerDN(authorityX509Name);
                s_certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                s_certGenerator.SetSubjectDN(subjectName);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            s_certGenerator.SetSerialNumber(serialNum);
            s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            s_certGenerator.SetPublicKey(keyPair.Public);

            s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            if (isAuthority || certificateCreationSettings.IncludeCrlDistributionPoint)
            {
                var crlDistributionPoints = new DistributionPoint[1]
                {
                    new DistributionPoint(
                        new DistributionPointName(
                            new GeneralNames(
                                new GeneralName(
                                    GeneralName.UniformResourceIdentifier, string.Format("{0}", _crlUri, serialNum.ToString(radix: 16))))),
                        null,
                        null)
                };
                var revocationListExtension = new CrlDistPoint(crlDistributionPoints);
                s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);
            }

            X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }