Example #1
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string name, string?testName = null)
        {
            X509Certificate2Collection chain = new X509Certificate2Collection();

            X509ExtensionCollection extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(name);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(s_tlsServerEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority intermediate,
                out X509Certificate2 endEntity,
                subjectName: name,
                testName: testName,
                keySize: 2048,
                extensions: extensions);

            chain.Add(intermediate.CloneIssuerCert());
            chain.Add(root.CloneIssuerCert());

            responder.Dispose();
            root.Dispose();
            intermediate.Dispose();

            return(endEntity, chain);
        }
Example #2
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string?testName = null, bool longChain = false, bool serverCertificate = true)
        {
            const int keySize = 2048;

            if (PlatformDetection.IsWindows && testName != null)
            {
                CleanupCertificates(testName);
            }

            X509Certificate2Collection chain      = new X509Certificate2Collection();
            X509ExtensionCollection    extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(targetName);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority[] intermediates,
Example #3
0
        private static X509ExtensionCollection BuildTlsCertExtensions(string targetName, bool serverCertificate)
        {
            X509ExtensionCollection extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(targetName);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);

            return(extensions);
        }
Example #4
0
        public static X509Certificate2 CreateSelfSignedCertificate(string subject)
        {
            var oids = new OidCollection();

            oids.Add(new Oid("1.3.6.1.5.5.7.3.2")); // client auth

            var extensions = new X509ExtensionCollection();

            extensions.Add(new X509EnhancedKeyUsageExtension(oids, true));

            var cgr = new CertificateGenerationRequest()
            {
                Subject          = subject,
                Extensions       = extensions,
                ExpirationLength = TimeSpan.FromDays(365 * 5),
                KeySize          = 2048
            };

            var cert = CertificateGenerator.CreateSelfSignedCertificate(cgr);

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
            }
            finally
            {
                store.Close();
            }

            return(cert);
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidDataException"></exception>
        public static X509ExtensionCollection DecodeX509Extensions(Byte[] rawData)
        {
            if (rawData == null)
            {
                throw new ArgumentNullException("rawData");
            }
            Asn1Reader asn = new Asn1Reader(rawData);

            if (asn.Tag != 48)
            {
                throw new InvalidDataException();
            }
            X509ExtensionCollection exts = new X509ExtensionCollection();

            if (!asn.MoveNext())
            {
                throw new Asn1InvalidTagException();
            }
            if (asn.NextOffset == 0)
            {
                return(exts);
            }
            do
            {
                exts.Add(DecodeX509Extension(asn.GetTagRawData()));
            } while (asn.MoveNextCurrentLevel());
            return(exts);
        }
Example #6
0
        public X509ExtensionCollection GetExtensions()
        {
            var coll = new X509ExtensionCollection();

            if (!HasExtensions)
            {
                return(coll);
            }

            X509ExtensionAsn[] rawExtensions = _parsedData.Extensions;

            foreach (X509ExtensionAsn rawExtension in rawExtensions)
            {
                X509Extension extension = new X509Extension(
                    rawExtension.ExtnId,
                    rawExtension.ExtnValue.ToArray(),
                    rawExtension.Critical);

                // Currently there are no extensions defined.
                // Should this dip into CryptoConfig or other extensible
                // mechanisms for the CopyTo rich type uplift?
                coll.Add(extension);
            }

            return(coll);
        }
 void getAttributes(Asn1Reader asn)
 {
     asn.MoveNext();
     if (asn.PayloadLength == 0)
     {
         return;
     }
     do
     {
         X509Attribute attribute = X509Attribute.Decode(asn.GetTagRawData());
         if (attribute.Oid.Value == X509ExtensionOid.CertificateExtensions)
         {
             //Extensions
             var extensions = new X509ExtensionCollection();
             extensions.Decode(attribute.RawData);
             foreach (X509Extension extension in extensions)
             {
                 _extensions.Add(extension);
             }
         }
         else
         {
             _attributes.Add(attribute);
         }
     } while (asn.MoveNextCurrentLevel());
 }
        public void Indexer_Int()
        {
            X509ExtensionCollection c = new X509ExtensionCollection();

            c.Add(extn_empty);
            Assert.AreEqual(extn_empty, c[0], "0");
        }
        /// <summary>
        /// Decodes ASN.1-encoded byte array that represents a collection of <see cref="X509Extension"/> objects.
        /// </summary>
        /// <param name="extensions">Destination collection where decoded extensions will be added.</param>
        /// <param name="rawData">ASN.1-encoded byte array that represents extension collection.</param>
        /// <exception cref="Asn1InvalidTagException">Decoder encountered an unexpected ASN.1 type identifier.</exception>
        /// <exception cref="ArgumentNullException">
        /// <strong>extensions</strong> and/or <strong>rawData</strong> parameter is null.
        /// </exception>
        /// <remarks>If current collection contains items, decoded items will be appended to existing items.</remarks>
        public static void Decode(this X509ExtensionCollection extensions, Byte[] rawData)
        {
            if (extensions == null)
            {
                throw new ArgumentNullException(nameof(extensions));
            }
            if (rawData == null)
            {
                throw new ArgumentNullException(nameof(rawData));
            }

            Asn1Reader asn = new Asn1Reader(rawData);

            if (asn.Tag != 48)
            {
                throw new Asn1InvalidTagException();
            }
            if (!asn.MoveNext() || asn.NextOffset == 0)
            {
                return;
            }

            do
            {
                extensions.Add(X509ExtensionExtensions.Decode(asn.GetTagRawData()));
            } while (asn.MoveNextCurrentLevel());
        }
        public void Add()
        {
            X509ExtensionCollection c = new X509ExtensionCollection();

            Assert.AreEqual(0, c.Count, "Count-0");
            c.Add(extn_empty);
            Assert.AreEqual(1, c.Count, "Count-1");
        }
        public void Indexer_String()
        {
            X509ExtensionCollection c = new X509ExtensionCollection();

            c.Add(extn_empty);
            Assert.IsNull(c[String.Empty]);
            Assert.IsNull(c ["1.2.3"]);
            Assert.AreEqual(extn_empty, c["1.2"], "0");
        }
        public void ICollection_CopyTo()
        {
            X509ExtensionCollection c = new X509ExtensionCollection();

            c.Add(extn_empty);
            X509Extension[] array = new X509Extension[1];
            (c as ICollection).CopyTo(array, 0);
            Assert.AreEqual(extn_empty, array[0], "0");
        }
Example #13
0
        /// <summary>
        /// Generate a self-signed CA certificate
        /// </summary>
        /// <param name="subject">The X500 subject string</param>
        /// <param name="rsaKeySize">The size of the RSA key to generate</param>
        /// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        /// <returns>An X509Certificate2 object containing the full certificate</returns>
        public static X509Certificate2 GenerateCACert(string subject, int rsaKeySize, CertificateHashAlgorithm hashAlgorithm)
        {
            X509ExtensionCollection exts = new X509ExtensionCollection();
            DateTime dt = DateTime.Now.AddYears(-1);

            exts.Add(new X509BasicConstraintsExtension(true, false, 0, false));

            return(builder.CreateCert(null, new X500DistinguishedName(subject), null, false, rsaKeySize, hashAlgorithm, dt, dt.AddYears(10), exts));
        }
Example #14
0
        internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string?testName = null)
        {
            if (PlatformDetection.IsWindows && testName != null)
            {
                CleanupCertificates(testName);
            }

            X509Certificate2Collection chain      = new X509Certificate2Collection();
            X509ExtensionCollection    extensions = new X509ExtensionCollection();

            SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();

            builder.AddDnsName(targetName);
            extensions.Add(builder.Build());
            extensions.Add(s_eeConstraints);
            extensions.Add(s_eeKeyUsage);
            extensions.Add(s_tlsServerEku);

            CertificateAuthority.BuildPrivatePki(
                PkiOptions.IssuerRevocationViaCrl,
                out RevocationResponder responder,
                out CertificateAuthority root,
                out CertificateAuthority intermediate,
                out X509Certificate2 endEntity,
                subjectName: targetName,
                testName: testName,
                keySize: 2048,
                extensions: extensions);

            chain.Add(intermediate.CloneIssuerCert());
            chain.Add(root.CloneIssuerCert());

            responder.Dispose();
            root.Dispose();
            intermediate.Dispose();

            if (PlatformDetection.IsWindows)
            {
                endEntity = new X509Certificate2(endEntity.Export(X509ContentType.Pfx));
            }

            return(endEntity, chain);
        }
 public static void AddRange(this X509ExtensionCollection exts, IEnumerable <X509Extension> extensions)
 {
     if (exts == null)
     {
         return;
     }
     foreach (X509Extension e in extensions)
     {
         exts.Add(e);
     }
 }
Example #16
0
 /// <summary>
 /// Create a CRL builder initialized with a decoded CRL.
 /// </summary>
 /// <param name="crl">The decoded CRL</param>
 private CrlBuilder(IX509CRL crl)
 {
     IssuerName            = crl.IssuerName;
     HashAlgorithmName     = crl.HashAlgorithmName;
     ThisUpdate            = crl.ThisUpdate;
     NextUpdate            = crl.NextUpdate;
     RawData               = crl.RawData;
     m_revokedCertificates = new List <RevokedCertificate>(crl.RevokedCertificates);
     m_crlExtensions       = new X509ExtensionCollection();
     foreach (var extension in crl.CrlExtensions)
     {
         m_crlExtensions.Add(extension);
     }
 }
Example #17
0
        private static X509Certificate2 CreateCertificateAuthority()
        {
            CspParameters parameters = new CspParameters()
            {
                ProviderName     = "Microsoft Enhanced RSA and AES Cryptographic Provider",
                ProviderType     = 24,
                KeyContainerName = Guid.NewGuid().ToString(),
                KeyNumber        = (int)KeyNumber.Signature,
                Flags            = CspProviderFlags.UseMachineKeyStore
            };

            var extensions = new X509ExtensionCollection();

            extensions.Add(new X509BasicConstraintsExtension(true, false, 0, false));
            extensions.Add(new X509KeyUsageExtension(
                               X509KeyUsageFlags.CrlSign |
                               X509KeyUsageFlags.DataEncipherment |
                               X509KeyUsageFlags.DigitalSignature |
                               X509KeyUsageFlags.KeyAgreement |
                               X509KeyUsageFlags.KeyCertSign |
                               X509KeyUsageFlags.KeyEncipherment |
                               X509KeyUsageFlags.NonRepudiation, false));

            var cgr = new CertificateGenerationRequest()
            {
                Subject            = "Syfuhs Industries Certificate Authority",
                Parameters         = parameters,
                SignatureAlgorithm = "1.2.840.113549.1.1.11",
                ExpirationLength   = TimeSpan.FromDays(365 * 20),
                KeySize            = 2048,
                Extensions         = extensions
            };

            var cert = CertificateGenerator.CreateSelfSignedCertificate(cgr);

            return(cert);
        }
 /// <summary>
 /// Adds a collection of <see cref="X509Extension"/> objects to existing collection.
 /// </summary>
 /// <param name="extensions">Destination collection where items will be added.</param>
 /// <param name="itemsToAdd">A source collection of items to add to destination.</param>
 /// <exception cref="ArgumentNullException">
 /// <strong>extensions</strong> and/or <strong>itemsToAdd</strong> is null.
 /// </exception>
 public static void AddRange(this X509ExtensionCollection extensions, IEnumerable <X509Extension> itemsToAdd)
 {
     if (extensions == null)
     {
         throw new ArgumentNullException(nameof(extensions));
     }
     if (itemsToAdd == null)
     {
         throw new ArgumentNullException(nameof(itemsToAdd));
     }
     foreach (X509Extension e in itemsToAdd)
     {
         extensions.Add(e);
     }
 }
Example #19
0
 /// <summary>
 /// Create CRL from IX509CRL interface.
 /// </summary>
 /// <param name="crl"></param>
 public X509CRL(IX509CRL crl)
 {
     m_decoded             = true;
     m_issuerName          = crl.IssuerName;
     m_hashAlgorithmName   = crl.HashAlgorithmName;
     m_thisUpdate          = crl.ThisUpdate;
     m_nextUpdate          = crl.NextUpdate;
     m_revokedCertificates = new List <RevokedCertificate>(crl.RevokedCertificates);
     m_crlExtensions       = new X509ExtensionCollection();
     foreach (var extension in crl.CrlExtensions)
     {
         m_crlExtensions.Add(extension);
     }
     RawData = crl.RawData;
 }
        internal static void RemoveAt(this X509ExtensionCollection exts, Int32 index)
        {
            if (exts == null || index >= exts.Count)
            {
                return;
            }
            List <X509Extension> e = new List <X509Extension>(exts.Cast <X509Extension>());

            e.RemoveAt(index);
            exts = new X509ExtensionCollection();
            foreach (X509Extension ext in e)
            {
                exts.Add(ext);
            }
        }
 void processExtensions()
 {
     foreach (X509Extension extension in Extensions)
     {
         if (_excludedExtensions.Contains(extension.Oid.Value))
         {
             continue;
         }
         _extensions.Add(extension.ConvertExtension());
     }
     finalExtensions = new X509ExtensionCollection();
     foreach (var extension in _extensions)
     {
         finalExtensions.Add(extension);
     }
 }
        /// <summary>
        /// Returns all extensions
        /// </summary>
        /// <returns></returns>
        private X509ExtensionCollection GetExtensions()
        {
            var extensions = new X509ExtensionCollection();
            var attr       = GetAttribute(OidAttributes.Extension);

            if (attr != null)
            {
                var asn1Object   = Asn1Object.FromByteArray(attr.Values[0].RawData);
                var asn1Sequence = Asn1Sequence.GetInstance(asn1Object);
                foreach (Asn1Encodable item in asn1Sequence)
                {
                    var ext = QualificationExtension(item);
                    extensions.Add(ext);
                }
            }
            return(extensions);
        }
 void decodePkcs7()
 {
     ExternalData       = new PKCS7SignedMessage(RawData);
     Version            = ((X509CertificateRequest[])ExternalData.Content)[0].Version;
     SubjectDn          = ((X509CertificateRequest[])ExternalData.Content)[0].SubjectDn;
     PublicKey          = ((X509CertificateRequest[])ExternalData.Content)[0].PublicKey;
     SignatureIsValid   = ((X509CertificateRequest[])ExternalData.Content)[0].SignatureIsValid;
     SignatureAlgorithm = ((X509CertificateRequest[])ExternalData.Content)[0].SignatureAlgorithm;
     foreach (X509Attribute attrib in ((X509CertificateRequest[])ExternalData.Content)[0].Attributes)
     {
         _attribs.Add(attrib);
     }
     foreach (X509Extension ext in ((X509CertificateRequest[])ExternalData.Content)[0].Extensions)
     {
         exts.Add(ext);
     }
 }
Example #24
0
        /// <summary>
        /// Take an existing certificate, clone its details and resign with a new root CA
        /// </summary>
        /// <param name="toClone">The certificate to clone</param>
        /// <param name="rootCert">The root CA certificate to sign with</param>
        /// <param name="newSerial">True to generate a new serial for this certificate</param>
        /// <param name="rsaKeySize">The size of the RSA key to generate</param>
        /// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        /// <returns></returns>
        public static X509Certificate2 CloneAndSignCertificate(X509Certificate toClone, X509Certificate2 rootCert, bool newSerial, int rsaKeySize, CertificateHashAlgorithm hashAlgorithm)
        {
            X509Certificate2        cert2      = new X509Certificate2(toClone.Export(X509ContentType.Cert));
            X509ExtensionCollection extensions = new X509ExtensionCollection();

            foreach (var ext in cert2.Extensions)
            {
                // Remove CRL distribution locations and authority information, they tend to break SSL negotiation
                if ((ext.Oid.Value != szOID_CRL_DISTRIBUTION) && (ext.Oid.Value != szOID_AUTHORITY_INFO))
                {
                    extensions.Add(ext);
                }
            }

            return(CertificateBuilder.CreateCert(rootCert, cert2.SubjectName, newSerial ? null : cert2.GetSerialNumber(),
                                                 rsaKeySize, hashAlgorithm, cert2.NotBefore, cert2.NotAfter, extensions));
        }
        /// <summary>
        /// Converts generic X.509 extension objects to specialized certificate extension objects
        /// inherited from <see cref="X509Extension"/> class that provide extension-specific information.
        /// </summary>
        /// <param name="cert">Certificate.</param>
        /// <exception cref="ArgumentNullException">
        /// <strong>cert</strong> parameter is null reference.
        /// </exception>
        /// <returns>A collection of certificate extensions</returns>
        /// <remarks>
        /// This method can transform the following X.509 certificate extensions:
        /// <list type="bullet">
        /// <item><description><see cref="X509CertificateTemplateExtension"/></description></item>
        /// <item><description><see cref="X509ApplicationPoliciesExtension"/></description></item>
        /// <item><description><see cref="X509ApplicationPolicyMappingsExtension"/></description></item>
        /// <item><description><see cref="X509ApplicationPolicyConstraintsExtension"/></description></item>
        /// <item><description><see cref="X509AuthorityInformationAccessExtension"/></description></item>
        /// <item><description><see cref="X509NonceExtension"/></description></item>
        /// <item><description><see cref="X509CRLReferenceExtension"/></description></item>
        /// <item><description><see cref="X509ArchiveCutoffExtension"/></description></item>
        /// <item><description><see cref="X509ServiceLocatorExtension"/></description></item>
        /// <item><description><see cref="X509SubjectKeyIdentifierExtension"/></description></item>
        /// <item><description><see cref="X509KeyUsageExtension"/></description></item>
        /// <item><description><see cref="X509SubjectAlternativeNamesExtension"/></description></item>
        /// <item><description><see cref="X509IssuerAlternativeNamesExtension"/></description></item>
        /// <item><description><see cref="X509BasicConstraintsExtension"/></description></item>
        /// <item><description><see cref="X509CRLNumberExtension"/></description></item>
        /// <item><description><see cref="X509NameConstraintsExtension"/></description></item>
        /// <item><description><see cref="X509CRLDistributionPointsExtension"/></description></item>
        /// <item><description><see cref="X509CertificatePoliciesExtension"/></description></item>
        /// <item><description><see cref="X509CertificatePolicyMappingsExtension"/></description></item>
        /// <item><description><see cref="X509AuthorityKeyIdentifierExtension"/></description></item>
        /// <item><description><see cref="X509CertificatePolicyConstraintsExtension"/></description></item>
        /// <item><description><see cref="X509EnhancedKeyUsageExtension"/></description></item>
        /// <item><description><see cref="X509FreshestCRLExtension"/></description></item>
        /// </list>
        /// Non-supported extensions will be returned as an <see cref="X509Extension"/> object.
        /// </remarks>
        public static X509ExtensionCollection ResolveExtensions(this X509Certificate2 cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }
            if (cert.Extensions.Count == 0)
            {
                return(cert.Extensions);
            }
            X509ExtensionCollection extensions = new X509ExtensionCollection();

            foreach (var ext in cert.Extensions)
            {
                extensions.Add(ext.ConvertExtension());
            }
            return(extensions);
        }
        internal static X509ExtensionCollection ShallowCopy(X509ExtensionCollection existing, bool preserveNull)
        {
            if (preserveNull && existing == null)
            {
                return(null);
            }

            var coll = new X509ExtensionCollection();

            if (existing == null)
            {
                return(coll);
            }

            foreach (var extn in existing)
            {
                coll.Add(extn);
            }

            return(coll);
        }
Example #27
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 CreateSubordinate()
        {
            var oids = new OidCollection();

            oids.Add(new Oid("1.3.6.1.5.5.7.3.2"));      // client auth
            oids.Add(new Oid("1.3.6.1.4.1.311.20.2.2")); // smart card login

            var extensions = new X509ExtensionCollection();

            extensions.Add(new X509EnhancedKeyUsageExtension(oids, true));

            var cgr = new CertificateGenerationRequest()
            {
                Subject          = "*****@*****.**",
                Extensions       = extensions,
                ExpirationLength = TimeSpan.FromDays(365 * 5),
                KeySize          = 2048
            };

            var cert = CertificateGenerator.CreateSelfSignedCertificate(cgr);

            return(cert);
        }
        /// <summary>
        /// Decodes ASN.1-encoded byte array that represents a collection of <see cref="X509Extension"/> objects.
        /// </summary>
        /// <param name="extensions">Destination collection where decoded extensions will be added.</param>
        /// <param name="asn">ASN.1 reader which points to the beginning of the extenstion collection structure.</param>
        /// <exception cref="Asn1InvalidTagException">Decoder encountered an unexpected ASN.1 type identifier.</exception>
        /// <exception cref="ArgumentNullException">
        /// <strong>extensions</strong> and/or <strong>asn</strong> parameter is null.
        /// </exception>
        /// <remarks> If current collection contains items, decoded items will be appended to existing items.</remarks>
        public static void Decode(this X509ExtensionCollection extensions, Asn1Reader asn)
        {
            if (extensions == null)
            {
                throw new ArgumentNullException(nameof(extensions));
            }
            if (asn == null)
            {
                throw new ArgumentNullException(nameof(asn));
            }
            Int32 offset = asn.Offset;

            if (!asn.MoveNext() || asn.PayloadLength == 0)
            {
                return;
            }

            do
            {
                extensions.Add(X509ExtensionExtensions.Decode(asn));
            } while (asn.MoveNextSibling());
            asn.Seek(offset);
        }
Example #29
0
        private void buttonCreate_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            int rsaKeySize = 0;

            if (radioButtonSimpleCN.Checked && String.IsNullOrWhiteSpace(textBoxCN.Text))
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyCN,
                                CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (radioButtonTemplate.Checked && _templateCert == null)
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyTemplate,
                                CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (radioButtonSpecifyCA.Checked && _specifyCert == null)
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyCA,
                                CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (!int.TryParse(comboBoxRsaKeySize.Text, out rsaKeySize))
            {
                MessageBox.Show(this, CANAPE.Properties.Resources.CreateCertForm_MustSpecifyAValidRSAKeySize,
                                CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    X509Certificate2 rootCert = null;

                    if (radioButtonSpecifyCA.Checked)
                    {
                        rootCert = _specifyCert;
                    }
                    else if (radioButtonDefaultCA.Checked)
                    {
                        rootCert = CertManager.GetRootCert();
                    }
                    else
                    {
                        // Self signed
                    }

                    if (radioButtonTemplate.Checked)
                    {
                        Certificate = CertificateUtils.CloneAndSignCertificate(_templateCert, rootCert, false, rsaKeySize, (CertificateHashAlgorithm)comboBoxHash.SelectedItem);
                    }
                    else
                    {
                        X509ExtensionCollection exts = new X509ExtensionCollection();
                        if (checkBoxCA.Checked)
                        {
                            exts.Add(new X509BasicConstraintsExtension(true, false, 0, true));
                        }

                        DateTime notBefore = DateTime.Now.Subtract(TimeSpan.FromDays(1));
                        Certificate = CertificateUtils.CreateCert(rootCert,
                                                                  new X500DistinguishedName(radioButtonSubject.Checked ? textBoxCN.Text : String.Format("CN={0}", textBoxCN.Text)), null, false, rsaKeySize,
                                                                  (CertificateHashAlgorithm)comboBoxHash.SelectedItem, notBefore, notBefore.AddYears(10), exts);
                    }
                }
                catch (Win32Exception ex)
                {
                    MessageBox.Show(ex.Message, CANAPE.Properties.Resources.MessageBox_ErrorString,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (CryptographicException ex)
                {
                    MessageBox.Show(ex.Message, CANAPE.Properties.Resources.MessageBox_ErrorString,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 public void Add_Null()
 {
     empty.Add(null);
 }