Exemple #1
0
        /// <summary>
        /// Generates the TBS cert.
        /// </summary>
        /// <param name="Extensions">The extensions.</param>
        /// <returns></returns>
        protected TbsCertificateStructure GenerateTbsCert(X509Extensions Extensions)
        {
            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            if (Extensions != null)
            {
                tbsGen.SetExtensions(Extensions);
            }

            return(tbsGen.GenerateTbsCertificate());
        }
        private void TbsV3CertGenerate()
        {
            V3TbsCertificateGenerator gen = new V3TbsCertificateGenerator();
            DateTime startDate            = MakeUtcDateTime(1970, 1, 1, 0, 0, 1);
            DateTime endDate = MakeUtcDateTime(1970, 1, 1, 0, 0, 2);

            gen.SetSerialNumber(new DerInteger(2));

            gen.SetStartDate(new Time(startDate));
            gen.SetEndDate(new Time(endDate));

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));
            gen.SetSubject(new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5WithRsaEncryption, DerNull.Instance));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                new AlgorithmIdentifier(
                    OiwObjectIdentifiers.ElGamalAlgorithm,
                    new ElGamalParameter(BigInteger.One, BigInteger.Two)),
                new DerInteger(3));

            gen.SetSubjectPublicKeyInfo(info);

            //
            // add extensions
            //
            IList       order      = new ArrayList();
            IDictionary extensions = new Hashtable();

            order.Add(X509Extensions.AuthorityKeyIdentifier);
            order.Add(X509Extensions.SubjectKeyIdentifier);
            order.Add(X509Extensions.KeyUsage);

            extensions.Add(X509Extensions.AuthorityKeyIdentifier, new X509Extension(true, new DerOctetString(CreateAuthorityKeyId(info, new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"), 2))));
            extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(true, new DerOctetString(new SubjectKeyIdentifier(info))));
            extensions.Add(X509Extensions.KeyUsage, new X509Extension(false, new DerOctetString(new KeyUsage(KeyUsage.DataEncipherment))));

            X509Extensions ex = new X509Extensions(order, extensions);

            gen.SetExtensions(ex);

            TbsCertificateStructure tbs = gen.GenerateTbsCertificate();

            if (!Arrays.AreEqual(tbs.GetEncoded(), v3Cert))
            {
                Fail("failed v3 cert generation");
            }

            //
            // read back test
            //
            Asn1Object o = Asn1Object.FromByteArray(v3Cert);

            if (!Arrays.AreEqual(o.GetEncoded(), v3Cert))
            {
                Fail("failed v3 cert read back test");
            }
        }
Exemple #3
0
        private TbsCertificateStructure GenerateTbsCert()
        {
            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            return(tbsGen.GenerateTbsCertificate());
        }
Exemple #4
0
        public static void CreateCert(string parentcer, string csrFile)
        {
            var issuer = new X509CertificateParser().ReadCertificate(File.OpenRead(parentcer));

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

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

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

            DateTime to = from.AddYears(5);


            V3TbsCertificateGenerator tbsGen = new V3TbsCertificateGenerator();

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

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

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

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

            tbsGen.SetExtensions(extGenerator.Generate());

            tbsGen.SetSignature(sigAlgId);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

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

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

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

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

            Console.WriteLine("saved as cert.cer");
        }
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
        }
Exemple #6
0
        private static TbsCertificateStructure CreateTbsForVerification(X509Certificate2 preCertificate, IssuerInformation issuerInformation)
        {
            if (preCertificate.Version < 3)
            {
                throw new InvalidOperationException("PreCertificate version must be 3 or higher!");
            }

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

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

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

            var generator = new V3TbsCertificateGenerator();

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

            var extensionsGenerator = new X509ExtensionsGenerator();

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

            generator.SetExtensions(extensionsGenerator.Generate());

            return(generator.GenerateTbsCertificate());
        }
        private void TbsV3CertGenWithNullSubject()
        {
            V3TbsCertificateGenerator gen = new V3TbsCertificateGenerator();
            DateTime startDate            = MakeUtcDateTime(1970, 1, 1, 0, 0, 1);
            DateTime endDate = MakeUtcDateTime(1970, 1, 1, 0, 0, 2);

            gen.SetSerialNumber(new DerInteger(2));

            gen.SetStartDate(new Time(startDate));
            gen.SetEndDate(new Time(endDate));

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5WithRsaEncryption, DerNull.Instance));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm,
                                        new ElGamalParameter(BigInteger.One, BigInteger.Two)),
                new DerInteger(3));

            gen.SetSubjectPublicKeyInfo(info);

            try
            {
                gen.GenerateTbsCertificate();
                Fail("null subject not caught!");
            }
            catch (InvalidOperationException e)
            {
                if (!e.Message.Equals("not all mandatory fields set in V3 TBScertificate generator"))
                {
                    Fail("unexpected exception", e);
                }
            }

            //
            // add extensions
            //
            IList       order      = new ArrayList();
            IDictionary extensions = new Hashtable();

            order.Add(X509Extensions.SubjectAlternativeName);

            extensions.Add(
                X509Extensions.SubjectAlternativeName,
                new X509Extension(
                    true,
                    new DerOctetString(
                        new GeneralNames(
                            new GeneralName(
                                new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"))))));

            X509Extensions ex = new X509Extensions(order, extensions);

            gen.SetExtensions(ex);

            TbsCertificateStructure tbs = gen.GenerateTbsCertificate();

            if (!Arrays.AreEqual(tbs.GetEncoded(), v3CertNullSubject))
            {
                Fail("failed v3 null sub cert generation");
            }

            //
            // read back test
            //
            Asn1Object o = Asn1Object.FromByteArray(v3CertNullSubject);

            if (!Arrays.AreEqual(o.GetEncoded(), v3CertNullSubject))
            {
                Fail("failed v3 null sub cert read back test");
            }
        }