private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        {
            TbsCertificateStructure certificate;

            using (Asn1InputStream input = new Asn1InputStream(x509certificate.GetTbsCertificate()))
            {
                certificate = TbsCertificateStructure.GetInstance(input.ReadObject());
            }

            AlgorithmIdentifier algorithmId = certificate.SubjectPublicKeyInfo.AlgorithmID;

            var             serial = new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(certificate.Issuer, certificate.SerialNumber.Value);
            IBufferedCipher cipher;

            try
            {
                cipher = CipherUtilities.GetCipher(algorithmId.Algorithm.Id);
            }
            catch (Exception e)
            {
                // should never happen, if this happens throw IOException instead
                throw new Exception("Could not find a suitable javax.crypto provider", e);
            }

            cipher.Init(true, x509certificate.GetPublicKey());

            DerOctetString      octets      = new DerOctetString(cipher.DoFinal(abyte0));
            RecipientIdentifier recipientId = new RecipientIdentifier(serial);

            return(new KeyTransRecipientInfo(recipientId, algorithmId, octets));
        }
Exemple #2
0
        /// <summary>
        /// Generate an X509Certificate.
        /// </summary>
        /// <param name="cspParam">CspParameters instance that has the private signing key</param>
        /// <param name="Extensions">Extensions to include in the certificate</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(CspParameters cspParam, X509Extensions Extensions)
        {
            TbsCertificateStructure tbsCert = GenerateTbsCert(Extensions);

            // Check this complies with policy
            if (policy != null)
            {
                TestAgainstPolicy test = new TestAgainstPolicy(policy);
                if (!test.report(tbsCert))
                {
                    throw new PolicyEnforcementException(test.status.ToString());
                }
            }

            byte[] cert = tbsCert.GetEncoded();
            byte[] signature;

            try
            {
                signature = SysSigner.Sign(cert, cspParam, signatureAlgorithm);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature))));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
Exemple #3
0
        /// <summary>
        /// Generate an X509 Certificate
        /// </summary>
        /// <param name="cspParam">CspParameters instance that has the private signing key</param>
        /// <returns>An X509 Certificate</returns>
        public X509Certificate Generate(CspParameters cspParam)
        {
            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            byte[] cert = tbsCert.GetEncoded();
            byte[] signature;

            try
            {
                signature = SysSigner.Sign(cert, cspParam, signatureAlgorithm);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature))));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
Exemple #4
0
        /// <summary>
        /// Generate an X509Certificate.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param>
        /// <param name="Extensions">Set of extensions to include in the certificate.</param>
        /// <returns>
        /// An X509Certificate.
        /// </returns>
        /// <exception cref="PolicyEnforcementException">CA policy violation</exception>
        /// <exception cref="CertificateEncodingException">
        /// Exception encoding TBS cert
        /// or
        /// Exception producing certificate object
        /// </exception>
        public virtual X509Certificate Generate(AsymmetricKeyParameter privateKey, X509Extensions Extensions)
        {
            TbsCertificateStructure tbsCert = GenerateTbsCert(Extensions);

            // Check this complies with policy
            if (policy != null)
            {
                TestAgainstPolicy test = new TestAgainstPolicy(policy);
                if (!test.report(tbsCert))
                {
                    throw new PolicyEnforcementException(test.status.ToString());
                }
            }

            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOid, signatureAlgorithm, privateKey, null, tbsCert);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature))));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
Exemple #5
0
        /// <summary>
        /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
        /// <param name="random">The Secure Random you want to use.</param>
        /// <returns>An X509Certificate.</returns>
        private X509Certificate generate(SecureRandom random, AsymmetricKeyParameter privateKey)
        {
            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOID, signatureAlgorithm, (AsymmetricKeyParameter)privateKey, random, tbsCert);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Exception encoding TBS cert", e);
            }

            try
            {
                return(GenerateJcaObject(tbsCert, signature));
            }
            catch (CertificateParsingException e)
            {
                throw new CertificateEncodingException("Exception producing certificate object", e);
            }
        }
Exemple #6
0
        public X509Certificate Generate(AsymmetricKeyParameter privateKey, SecureRandom random)
        {
            TbsCertificateStructure tbsCertificateStructure = this.tbsGen.GenerateTbsCertificate();

            byte[] signatureForObject;
            try
            {
                signatureForObject = X509Utilities.GetSignatureForObject(this.sigOID, this.signatureAlgorithm, privateKey, random, tbsCertificateStructure);
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("exception encoding TBS cert", e);
            }
            X509Certificate result;

            try
            {
                result = this.GenerateJcaObject(tbsCertificateStructure, signatureForObject);
            }
            catch (CertificateParsingException e2)
            {
                throw new CertificateEncodingException("exception producing certificate object", e2);
            }
            return(result);
        }
        public static byte[] GetSubjectPublicKeyInfo(this System.Security.Cryptography.X509Certificates.X509Certificate certificate)
        {
            var cert    = new X509CertificateParser().ReadCertificate(certificate.GetRawCertData());
            var tbsCert = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));

            return(tbsCert.SubjectPublicKeyInfo.GetDerEncoded());
        }
Exemple #8
0
        internal override bool analyse(TbsCertificateStructure tbsCert)
        {
            bool status = true;

            BasicConstraints bc = BasicConstraints.GetInstance(tbsCert.Extensions.GetExtension(X509Extensions.BasicConstraints));

            // If CA PathLength == 0, then cannot issue CA certs
            if ((bc.IsCA()) && (pathLen == 0))
            {
                report = report + "CA PathLengthConstraint = 0 - cannot issue CA certificates;";
                status = false;
            }

            // If CA PathLength set cert PathLength must be <
            if ((bc.IsCA()) && (pathLen < int.MaxValue) && (bc.PathLenConstraint.IntValue >= pathLen))
            {
                report = report + "CA PathLengthConstraint = " + pathLen.ToString() + " - invalid certificate Path Length = " + bc.PathLenConstraint.IntValue.ToString() + ";";
                status = false;
            }

            // If CA PathLength set then cert must set a PathLength
            if ((bc.IsCA()) && (pathLen < int.MaxValue) && (bc.PathLenConstraint == null))
            {
                report = report + "CA PathLengthConstraint = " + pathLen.ToString() + " - certificate must set PathLengthConstraint;";
                status = false;
            }
            return(status);
        }
Exemple #9
0
        private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        {
            Asn1InputStream asn1inputstream =
                new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate()));
            TbsCertificateStructure tbscertificatestructure =
                TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject());
            AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID;

            Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerandserialnumber =
                new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(
                    tbscertificatestructure.Issuer,
                    tbscertificatestructure.SerialNumber.Value);
            IBufferedCipher cipher = CipherUtilities.GetCipher(algorithmidentifier.ObjectID);

            cipher.Init(true, x509certificate.GetPublicKey());
            byte[] outp = new byte[10000];
            int    len  = cipher.DoFinal(abyte0, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString      deroctetstring = new DerOctetString(abyte1);
            RecipientIdentifier recipId        = new RecipientIdentifier(issuerandserialnumber);

            return(new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring));
        }
Exemple #10
0
        /// <summary>
        /// Generate an X509Certificate using your own SecureRandom.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param>
        /// <param name="random">You Secure Random instance.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(
            AsymmetricKeyParameter privateKey,
            SecureRandom random)
        {
            TbsCertificateStructure tbsCert = GenerateTbsCert();

            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOid, signatureAlgorithm, privateKey, random, tbsCert);
            }
            catch (Exception e)
            {
                // TODO
//				throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
                throw new CertificateEncodingException("exception encoding TBS cert", e);
            }

            try
            {
                return(GenerateJcaObject(tbsCert, signature));
            }
            catch (CertificateParsingException e)
            {
                // TODO
                // throw new ExtCertificateEncodingException("exception producing certificate object", e);
                throw new CertificateEncodingException("exception producing certificate object", e);
            }
        }
Exemple #11
0
 private X509Certificate GenerateJcaObject(
     TbsCertificateStructure tbsCert,
     byte[]                                  signature)
 {
     return(new X509Certificate(
                new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature))));
 }
        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");
            }
        }
        /**
         * add a recipient.
         *
         * @param cert recipient's public key certificate
         * @exception ArgumentException if there is a problem with the certificate
         */
        public void AddKeyTransRecipient(
            X509Certificate cert)
        {
            TbsCertificateStructure recipientTbsCert = CmsUtilities.GetTbsCertificateStructure(cert);
            SubjectPublicKeyInfo    info             = recipientTbsCert.SubjectPublicKeyInfo;

            this.AddRecipientInfoGenerator(new KeyTransRecipientInfoGenerator(cert, new Asn1KeyWrapper(info.AlgorithmID.Algorithm, info.AlgorithmID.Parameters, cert)));
        }
Exemple #14
0
 static X509Certificate GenerateJcaObject(
     TbsCertificateStructure tbsCert,
     AlgorithmIdentifier sigAlg,
     byte[] signature)
 {
     return(new X509Certificate(
                new X509CertificateStructure(tbsCert, sigAlg, new DerBitString(signature))));
 }
Exemple #15
0
        public static void CreateCert(string parentcer, string csrFile)
        {
            var issuer = new X509CertificateParser().ReadCertificate(File.OpenRead(parentcer));

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

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

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

            DateTime to = from.AddYears(5);


            V3TbsCertificateGenerator tbsGen = new V3TbsCertificateGenerator();

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

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

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

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

            tbsGen.SetExtensions(extGenerator.Generate());

            tbsGen.SetSignature(sigAlgId);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

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

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

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

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

            Console.WriteLine("saved as cert.cer");
        }
Exemple #16
0
//			internal Asn1.Cms.AttributeTable SignedAttributes
//            {
//				get { return _sAttr; }
//            }
//
//			internal Asn1.Cms.AttributeTable UnsignedAttributes
//            {
//				get { return _unsAttr; }
//            }

            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
                AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);

                byte[] hash = DigestUtilities.DoFinal(_digest);

                outer._digests.Add(_digestOID, hash.Clone());

                IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

                Asn1.Cms.AttributeTable signed = (_sAttr != null)
//					?	_sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
                                        ?       _sAttr.GetAttributes(parameters)
                                        :       null;

                Asn1Set signedAttr = outer.GetAttributeSet(signed);

                //
                // sig must be composed from the DER encoding.
                //
                byte[] bOutBytes;
                if (signedAttr != null)
                {
                    bOutBytes = signedAttr.GetDerEncoded();
                }
                else
                {
                    throw new Exception("signatures without signed attributes not implemented.");
                }

                _signature.BlockUpdate(bOutBytes, 0, bOutBytes.Length);

                Asn1OctetString encDigest = new DerOctetString(_signature.GenerateSignature());

                parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

                Asn1.Cms.AttributeTable unsigned = (_unsAttr != null)
//					?	_unsAttr.getAttributes(Collections.unmodifiableMap(parameters))
                                        ?       _unsAttr.GetAttributes(parameters)
                                        :       null;

                Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate         cert = this.Certificate;
                TbsCertificateStructure tbs  = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(cert.GetTbsCertificate()));
                IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
                    tbs.Issuer, tbs.SerialNumber.Value);

                return(new SignerInfo(new SignerIdentifier(encSid), digAlgId,
                                      signedAttr, encAlgId, encDigest, unsignedAttr));
            }
Exemple #17
0
 private X509CertificateStructure(Asn1Sequence seq)
 {
     if (seq.Count != 3)
     {
         throw new ArgumentException("sequence wrong size for a certificate", "seq");
     }
     tbsCert  = TbsCertificateStructure.GetInstance(seq[0]);
     sigAlgID = AlgorithmIdentifier.GetInstance(seq[1]);
     sig      = DerBitString.GetInstance(seq[2]);
 }
 private void CheckMalformed()
 {
     try
     {
         TbsCertificateStructure cert = TbsCertificateStructure.GetInstance(bangerCert);
     }
     catch (ArgumentException e)
     {
         // expected - anything else is not!
     }
 }
Exemple #19
0
    public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
    {
        tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);
        TbsCertificateStructure tbsCertificateStructure = tbsGen.GenerateTbsCertificate();
        IStreamCalculator       streamCalculator        = signatureCalculatorFactory.CreateCalculator();

        byte[] derEncoded = tbsCertificateStructure.GetDerEncoded();
        streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
        Platform.Dispose(streamCalculator.Stream);
        return(GenerateJcaObject(tbsCertificateStructure, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
    }
Exemple #20
0
 internal static void CheckCertificate(X509Certificate cert)
 {
     try
     {
         TbsCertificateStructure.GetInstance(cert.CertificateStructure.TbsCertificate);
     }
     catch (CertificateEncodingException e)
     {
         throw new Exception("unable to process TBSCertificate", e);
     }
 }
        public byte[] GenerateDerEncodedUnsignedCertificate()
        {
            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            return(tbsCert.GetDerEncoded());
        }
Exemple #22
0
 public static X509Name GetIssuerX509Principal(X509Certificate cert)
 {
     try
     {
         TbsCertificateStructure instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));
         return(instance.Issuer);
     }
     catch (global::System.Exception e)
     {
         throw new CertificateEncodingException("Could not extract issuer", e);
     }
 }
 public static X509Name GetSubjectX509Principal(X509Certificate cert)
 {
     try
     {
         TbsCertificateStructure instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));
         return(instance.Subject);
     }
     catch (Exception e)
     {
         throw new CertificateEncodingException("Could not extract subject", e);
     }
 }
        private X509CertificateStructure(
            Asn1Sequence seq)
        {
            if (seq.Count != 3)
                throw new ArgumentException("sequence wrong size for a certificate", "seq");

            //
            // correct x509 certficate
            //
            tbsCert = TbsCertificateStructure.GetInstance(seq[0]);
            sigAlgID = AlgorithmIdentifier.GetInstance(seq[1]);
            sig = DerBitString.GetInstance(seq[2]);
        }
Exemple #25
0
        public static void SignCert(string tbsfile, string tbssig)
        {
            AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha256WithRsaEncryption);



            var t1 = GenerateJcaObject(
                TbsCertificateStructure.GetInstance(Asn1Sequence.FromByteArray(File.ReadAllBytes(tbsfile))), sigAlgId,
                System.IO.File.ReadAllBytes(tbssig).Take(256).ToArray());

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

            Console.WriteLine("saved as cert.cer");
        }
        public X509CertificateStructure(
            TbsCertificateStructure	tbsCert,
            AlgorithmIdentifier		sigAlgID,
            DerBitString			sig)
        {
            if (tbsCert == null)
                throw new ArgumentNullException("tbsCert");
            if (sigAlgID == null)
                throw new ArgumentNullException("sigAlgID");
            if (sig == null)
                throw new ArgumentNullException("sig");

            this.tbsCert = tbsCert;
            this.sigAlgID = sigAlgID;
            this.sig = sig;
        }
        /// <summary>
        /// Generate a new X509Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculator">A signature calculator with the necessary algorithm details.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(ISignatureCalculator signatureCalculator)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculator.AlgorithmDetails);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

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

            streamCalculator.Stream.Close();

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).DoFinal()));
        }
Exemple #28
0
        /// <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);

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCert.GetDerEncoded();

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

            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);

            return(GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()));
        }
Exemple #29
0
        internal bool report(TbsCertificateStructure tbsCert)
        {
            bool valid = true;
            int  index = 0;

            foreach (PolicyEnforcement module in policyModules)
            {
                if (!module.analyse(tbsCert))
                {
                    valid          = false;
                    _status[index] = module.result;
                    index++;
                }
            }

            return(valid);
        }
Exemple #30
0
        private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        {
            Asn1InputStream asn1inputstream = new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate()
                                                                                   ));
            TbsCertificateStructure tbscertificatestructure = TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject
                                                                                                      ());

            System.Diagnostics.Debug.Assert(tbscertificatestructure != null);
            AlgorithmIdentifier   algorithmidentifier   = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID;
            IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.Issuer, tbscertificatestructure
                                                                                    .SerialNumber.Value);

            byte[]              cipheredBytes  = EncryptionUtils.CipherBytes(x509certificate, abyte0, algorithmidentifier);
            DerOctetString      deroctetstring = new DerOctetString(cipheredBytes);
            RecipientIdentifier recipId        = new RecipientIdentifier(issuerandserialnumber);

            return(new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring));
        }
Exemple #31
0
 public X509CertificateStructure(TbsCertificateStructure tbsCert, AlgorithmIdentifier sigAlgID, DerBitString sig)
 {
     if (tbsCert == null)
     {
         throw new ArgumentNullException("tbsCert");
     }
     if (sigAlgID == null)
     {
         throw new ArgumentNullException("sigAlgID");
     }
     if (sig == null)
     {
         throw new ArgumentNullException("sig");
     }
     this.tbsCert  = tbsCert;
     this.sigAlgID = sigAlgID;
     this.sig      = sig;
 }
Exemple #32
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());
        }