Esempio n. 1
0
        /* public X509Certificate2 FindRootCertificate(X509Certificate2 serverX509Certificate2, IDictionary<string, X509Certificate2> rootCertificateDirectory)
         * {
         *   bool rootCertificateFound = false;
         *   X509Certificate2 desiredRootX509Certificate2 = null;
         *   // Find the desired root certificate
         *   X509Chain x509Chain = new X509Chain();
         *   x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
         *   x509Chain.Build(serverX509Certificate2);
         *
         *   // Iterate though the chain, to validate if it contain a valid root vertificate
         *   X509ChainElementCollection x509ChainElementCollection = x509Chain.ChainElements;
         *   X509ChainElementEnumerator enumerator = x509ChainElementCollection.GetEnumerator();
         *   X509ChainElement x509ChainElement;
         *   X509Certificate2 x509Certificate2 = null;
         *   string x509CertificateThumbprint;
         *   // At this point, the certificate is not valid, until a
         *   // it is proved that it has a valid root certificate
         *   while (rootCertificateFound == false && enumerator.MoveNext())
         *   {
         *       x509ChainElement = enumerator.Current;
         *       x509Certificate2 = x509ChainElement.Certificate;
         *       x509CertificateThumbprint = x509Certificate2.Thumbprint.ToLowerInvariant();
         *       if (rootCertificateDirectory.ContainsKey(x509CertificateThumbprint))
         *       {
         *           // The current chain element is in the trusted rootCertificateDirectory
         *           rootCertificateFound = true;
         *
         *           // now the loop will break, as we have found a trusted root certificate
         *       }
         *   }
         *
         *   if (rootCertificateFound)
         *   {
         *       // root certificate is found
         *       desiredRootX509Certificate2 = x509Certificate2;
         *   }
         *
         *   return desiredRootX509Certificate2;
         * }*/

        public List <string> GetAuthorityInformationAccessOcspUrl(X509Certificate2 x509Certificate2)
        {
            List <string> ocspUrls = new List <string>();

            try
            {
                // DanID test code shows how to do it
                Org.BouncyCastle.Asn1.X509.X509Extensions x509Extensions = this.GetX509Extensions(x509Certificate2);
                Org.BouncyCastle.Asn1.X509.X509Extension  x509Extension  = x509Extensions.GetExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityInfoAccess);
                if (x509Extension == null)
                {
                    // The desired info does not exist
                    // Meaning the certificate does not contain ocsp urls
                }
                else
                {
                    Org.BouncyCastle.Asn1.X509.AuthorityInformationAccess authorityInformationAccess = Org.BouncyCastle.Asn1.X509.AuthorityInformationAccess.GetInstance(x509Extension.GetParsedValue());
                    Org.BouncyCastle.Asn1.X509.AccessDescription[]        accessDescription          = authorityInformationAccess.GetAccessDescriptions();
                    string ocspUrl = this.GetAccessDescriptionUrlForOid(AccessDescription.IdADOcsp, accessDescription);
                    ocspUrls.Add(ocspUrl);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error parsing AIA.", e);
            }

            return(ocspUrls);
        }
Esempio n. 2
0
        public static ExtendedKeyUsage retrieveExtendedKeyUsageOIDs(X509Certificate x509Certificate)
        {
            ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage();

            X509Extension x509Extension = x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(new DerObjectIdentifier(OIDS.OID_EXTENDED_KEY_USAGE_EXTENSION));

            if (x509Extension != null)
            {
                Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage extendedKeyUsageExtension = Org.BouncyCastle.Asn1.X509.ExtendedKeyUsage.GetInstance(x509Extension);
                extendedKeyUsage.HasExtendedKeyUsageExtension = true;
                extendedKeyUsage.IsCritical = x509Extension.IsCritical;
                IList allUsages = extendedKeyUsageExtension.GetAllUsages();
                extendedKeyUsage.Count = allUsages.Count;

                List <byte[]> purposeOidList = new List <byte[]>(allUsages.Count);
                foreach (DerObjectIdentifier derObjectIdentifier in allUsages)
                {
                    purposeOidList.Add(StringUtil.StringToByteArray(derObjectIdentifier.Id));
                }

                extendedKeyUsage.Oids = purposeOidList.ToArray();
            }
            else
            {
                extendedKeyUsage.HasExtendedKeyUsageExtension = false;
            }

            return(extendedKeyUsage);
        }
Esempio n. 3
0
        public static SubjectKeyIdentifier retrieveSubjectKeyIdentifier(X509Certificate x509Certificate)
        {
            SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier();
            X509Extension        x509Extension        =
                x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(
                    new DerObjectIdentifier(OIDS.OID_SUBJECT_KEY_IDENTIFIER_EXTENSION));

            if (x509Extension != null)
            {
                Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier subjectKeyIdentifierExtension =
                    Org.BouncyCastle.Asn1.X509.SubjectKeyIdentifier.GetInstance(x509Extension);


                subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = true;
                subjectKeyIdentifier.IsCritical    = x509Extension.IsCritical;
                subjectKeyIdentifier.keyIdentifier = subjectKeyIdentifierExtension.GetKeyIdentifier();
                //todo: add issuer and serial fields.
            }
            else
            {
                subjectKeyIdentifier.HasSubjectKeyIdentifierExtension = false;
            }

            return(subjectKeyIdentifier);
        }
		public void AddExtension(
			string	oid,
			bool	critical,
			byte[]	value)
		{
			DerObjectIdentifier derOid = new DerObjectIdentifier(oid);
			extensions[derOid] = new X509Extension(critical, new DerOctetString(value));
			extOrdering.Add(derOid);
		}
Esempio n. 5
0
		/// <sumary>Convert the value of the passed in extension to an object.</sumary>
		/// <param name="ext">The extension to parse.</param>
		/// <returns>The object the value string contains.</returns>
		/// <exception cref="ArgumentException">If conversion is not possible.</exception>
		public static Asn1Object ConvertValueToObject(
			X509Extension ext)
		{
			try
			{
				return Asn1Object.FromByteArray(ext.Value.GetOctets());
			}
			catch (Exception e)
			{
				throw new ArgumentException("can't convert extension", e);
			}
		}
Esempio n. 6
0
        private static X509Extensions CreateExtension()
        {
            byte[]    nonce = new byte[16];
            Hashtable exts  = new Hashtable();

            BigInteger    nc       = BigInteger.ValueOf(DateTime.Now.Ticks);
            X509Extension nonceext = new X509Extension(false, new DerOctetString(nc.ToByteArray()));

            exts.Add(OcspObjectIdentifiers.PkixOcspNonce, nonceext);

            return(new X509Extensions(exts));
        }
Esempio n. 7
0
        /// <sumary>Convert the value of the passed in extension to an object.</sumary>
        /// <param name="ext">The extension to parse.</param>
        /// <returns>The object the value string contains.</returns>
        /// <exception cref="ArgumentException">If conversion is not possible.</exception>
        public static Asn1Object ConvertValueToObject(
			X509Extension ext)
        {
            try
            {
                return Asn1Object.FromByteArray(ext.Value.GetOctets());
            }
            catch (Exception e)
            {
                // MASC 20070307. CF compatibility patch
                throw new ArgumentException("can't convert extension:ext", e);
            }
        }
        /// <summary>
        /// Call to request a certificate
        /// </summary>
        /// <param name="csr">Certificate signing request</param>
        /// <param name="effectiveDate">Effective date of certificate</param>
        /// <param name="expirationDate">Expiration date of certificate</param>
        /// <param name="ca">Signing authority</param>
        /// <param name="asn1Set">Extensions</param>
        /// <exception cref="InvalidParameterException">Thrown if <paramref name="ca"/> is null</exception>
        /// <returns>Certificate signed by <paramref name="ca"/></returns>
        public static X509Certificate2 RequestCertificate(Pkcs10CertificationRequest csr, DateTime effectiveDate, DateTime expirationDate, X509Certificate2 ca, Asn1Set asn1Set)
        {
            AsymmetricKeyParameter keyParameter = null;

            if (ca == null)
            {
                throw new InvalidParameterException("ca can not be null");
            }

            keyParameter = TransformRSAPrivateKey((RSACryptoServiceProvider)ca.PrivateKey);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(CreateSerialNumber());
            certGen.SetIssuerDN(new X509Name(ca.Subject));
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());
            certGen.SetSubjectDN(csr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(csr.GetPublicKey());
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            if (asn1Set != null)
            {
                // Iterate through each extension and add it to the certificate
                for (int i = 0; i < asn1Set.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(asn1Set[i]);

                    if (attr != null && attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier extOid in extensions.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions.GetExtension(extOid);

                            certGen.AddExtension(extOid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(keyParameter);

            return(new X509Certificate2(bcCert.GetEncoded()));
        }
Esempio n. 9
0
        public static AuthorityKeyIdentifier retrieveAuthorityKeyIdentifier(X509Certificate x509Certificate)
        {
            AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifier();
            X509Extension          x509Extension          = x509Certificate.CertificateStructure.TbsCertificate.Extensions.GetExtension(new DerObjectIdentifier(OIDS.OID_AUTHORITY_KEY_IDENTIFIER_EXTENSION));

            if (x509Extension != null)
            {
                Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier authorityKeyIdentifierExtension = Org.BouncyCastle.Asn1.X509.AuthorityKeyIdentifier.GetInstance(x509Extension);
                authorityKeyIdentifier.HasAuthorityKeyIdentifier = true;
                authorityKeyIdentifier.IsCritical    = x509Extension.IsCritical;
                authorityKeyIdentifier.keyIdentifier = authorityKeyIdentifierExtension.GetKeyIdentifier();
                //todo: add issuer and serial fields.
            }
            else
            {
                authorityKeyIdentifier.HasAuthorityKeyIdentifier = false;
            }

            return(authorityKeyIdentifier);
        }
        // previous code found to cause a NullPointerException
        private void nullPointerTest()
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            IAsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair();

            IList oids = new ArrayList();
            IList values = new ArrayList();
            oids.Add(X509Extensions.BasicConstraints);
            values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true))));
            oids.Add(X509Extensions.KeyUsage);
            values.Add(new X509Extension(true, new DerOctetString(
                new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign))));
            SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public);
            X509Extension ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier));
            oids.Add(X509Extensions.SubjectKeyIdentifier);
            values.Add(ski);

            AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                new DerSet(new X509Extensions(oids, values)));

            Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);
            Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);

            if (!p1.Equals(p2))
            {
                Fail("cert request comparison failed");
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="cerRequest"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest cerRequest,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(rootCert.SubjectDN);
            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = cerRequest.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(cerRequest.GetPublicKey());

            AlgorithmIdentifier sigAlg = cerRequest.SignatureAlgorithm;
            string algName             = GetAlgorithmName(sigAlg.Algorithm.Id);

            certGen.SetSignatureAlgorithm(algName);

            // Add certificate extensions
            Asn1Set attributes = cerRequest.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);
                            certGen.AddExtension(oid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file sucessfully generated." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Check if generated certificate file is valid, plase wait ..." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
                issuedCert.CheckValidity(DateTime.UtcNow);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file is valid." + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            try
            {
                tbOutputMessageBox.Inlines.Add(new Run
                {
                    Text       = "Verify generated certificate file, plase wait ..." + "\n",
                    Foreground = System.Windows.Media.Brushes.Black
                });
                issuedCert.Verify(issuerKeyPair.Public);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Generate certificate file verification is OK." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            return(issuedCert);
        }
Esempio n. 12
0
        public override bool Equals(object obj)
        {
            X509Extension x509Extension = obj as X509Extension;

            return(x509Extension != null && this.Value.Equals(x509Extension.Value) && this.IsCritical == x509Extension.IsCritical);
        }
Esempio n. 13
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="csr"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest csr,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            //List<ExtensionsItem> extensions = null;

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(rootCert.SubjectDN);

            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(csr.GetPublicKey());

            var sigAlg  = csr.Signature;
            var sigAlg1 = csr.SignatureAlgorithm;

            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");


            // Add certificate extensions
            Asn1Set attributes = csr.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);

                            // !!! NOT working !!!
                            //certGen.AddExtension(oid, ext.IsCritical, ext.Value);

                            //OK
                            certGen.AddExtension(oid, ext.IsCritical, ext.Value, true);
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Check if generated certificate file is valid, plase wait ..." + "\n";
                issuedCert.CheckValidity(DateTime.UtcNow);
                tbOutputMessageBox.Text += "Generate certificate file is valid." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Verify generated certificate file, plase wait ..." + "\n";
                issuedCert.Verify(issuerKeyPair.Public);
                tbOutputMessageBox.Text += "Generate certificate file verification is OK." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            return(issuedCert);
        }
Esempio n. 14
0
        /**
         * return the parsed value of the extension represented by the object identifier
         * passed in.
         *
         * @return the parsed value of the extension if it's present, null otherwise.
         */
        public Asn1Encodable GetExtensionParsedValue(DerObjectIdentifier oid)
        {
            X509Extension ext = GetExtension(oid);

            return(ext == null ? null : ext.GetParsedValue());
        }
        public void GenerateUsingCsr()
        {
            var root = File.ReadAllBytes(@"root.pfx");
            X509KeyUsageExtension var = new X509KeyUsageExtension(
                X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.DecipherOnly | X509KeyUsageFlags.KeyCertSign, true);

            var x509RootCert = new X509Certificate2(root, "airwatch",
                                                    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            var randomGenerator  = new CryptoApiRandomGenerator();
            var random           = new SecureRandom(randomGenerator);
            var cert             = new X509V3CertificateGenerator();
            var csr              = string.Empty;
            var textReader       = new StringReader(csr);
            var reader           = new Org.BouncyCastle.OpenSsl.PemReader(textReader);
            var csrRequestObject = reader.ReadObject() as Pkcs10CertificationRequest;

            if (csrRequestObject != null)
            {
                var csrInfo = csrRequestObject.GetCertificationRequestInfo();
                csrInfo.SubjectPublicKeyInfo.GetPublicKey();
                cert.SetPublicKey(PublicKeyFactory.CreateKey(csrInfo.SubjectPublicKeyInfo));
            }
            cert.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage((int)0));
            var asn1EncodableVector = new Asn1EncodableVector
            {
                new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.1")
            };
            var derSeq = new DerSequence(asn1EncodableVector);

            cert.AddExtension(X509Extensions.AuthorityInfoAccess, false, derSeq);
            cert.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
            var  privatekey = x509RootCert.PrivateKey as RSACryptoServiceProvider;
            var  ss         = privatekey.ExportParameters(true);
            IRsa rsa        = new RsaCoreEngine();

            rsa.Init(true, new RsaKeyParameters(true, new BigInteger(1, ss.Modulus), new BigInteger(1, ss.Exponent)));
            //var signer = new RsaDigestSigner(rsa, new Sha512Digest(),
            //    new AlgorithmIdentifier(new DerObjectIdentifier("1.3.6.1.4.1.311.20.2.1")));

            //(signingKeyPair, properties.SignatureAlgorithm);
            X509Extension extension = new X509Extension(false, new DerOctetString(new AuthorityKeyIdentifierStructure(new X509Certificate(X509CertificateStructure.GetInstance(root)))));

            cert.AddExtension(X509Extensions.CertificateIssuer, true, new AuthorityKeyIdentifierStructure(new X509Certificate(X509CertificateStructure.GetInstance(root))));
            var serialNumber =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            cert.SetSerialNumber(serialNumber);

            var subjectDN = new X509Name("CN=test");

            cert.SetIssuerDN(subjectDN);
            cert.SetSubjectDN(subjectDN);

            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(10);

            cert.SetNotBefore(notBefore);
            cert.SetNotAfter(notAfter);

            const int strength = 2048;
            var       keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            cert.SetPublicKey(subjectKeyPair.Public);
            cert.SetSignatureAlgorithm("SHA256withRSA");


            var certificate = cert.Generate(subjectKeyPair.Private, random);

            var certexp = new X509Certificate2(certificate.GetEncoded(), "1234");

            certexp.Extensions.Add(var);
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadWrite);
            store.Add(certexp);
            File.WriteAllBytes(@"C:\cmstest\test.pfx", certexp
                               .Export(X509ContentType.Pfx, "1234"));
        }
Esempio n. 16
0
        private static Dictionary <DerObjectIdentifier, X509Extension> GetExtensionsWithoutPoisonAndSct(X509Extensions extensions, X509Extension replacementX509Authority)
        {
            var result = new Dictionary <DerObjectIdentifier, X509Extension>();

            foreach (DerObjectIdentifier oid in extensions.GetExtensionOids())
            {
                if (oid.Id != Constants.PoisonOid && oid.Id != Constants.SctCertificateOid)
                {
                    if (oid.Id == Constants.X509AuthorityKeyIdentifier && replacementX509Authority != null)
                    {
                        result.Add(oid, replacementX509Authority);
                    }
                    else
                    {
                        result.Add(oid, extensions.GetExtension(oid));
                    }
                }
            }

            return(result);
        }
Esempio n. 17
0
 public Asn1Encodable GetParsedValue()
 {
     return(X509Extension.ConvertValueToObject(this));
 }