Наследование: Org.BouncyCastle.Asn1.Asn1Encodable
Пример #1
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument
                                                      )
        {
            ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

            BcCms.ContentInfo contentInfo = cmsSignedData.ContentInfo;
            BcCms.SignedData  signedData  = BcCms.SignedData.GetInstance(contentInfo.Content);
            // 5.4.1
            if (signedData.EncapContentInfo == null || signedData.EncapContentInfo.
                Content == null)
            {
                if (originalDocument != null)
                {
                    //jbonilla Hack para leer un InputStream en su totalidad.
                    toTimestamp.Write(Streams.ReadAll(
                                          originalDocument.OpenStream()));
                }
                else
                {
                    throw new RuntimeException("Signature is detached and no original data provided."
                                               );
                }
            }
            else
            {
                BcCms.ContentInfo content = signedData.EncapContentInfo;
                DerOctetString    octet   = (DerOctetString)content.Content;
                BcCms.ContentInfo info2   = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"
                                                                                          ), new BerOctetString(octet.GetOctets()));
                toTimestamp.Write(info2.GetEncoded());
            }
            if (signedData.Certificates != null)
            {
                DerOutputStream output = new DerOutputStream(toTimestamp);
                output.WriteObject(signedData.Certificates);
                output.Close();
            }
            if (signedData.CRLs != null)
            {
                toTimestamp.Write(signedData.CRLs.GetEncoded());
            }
            if (signerInformation.UnsignedAttributes != null)
            {
                Asn1EncodableVector     original          = signerInformation.UnsignedAttributes.ToAsn1EncodableVector();
                IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index);
                Asn1EncodableVector     filtered          = new Asn1EncodableVector();
                for (int i = 0; i < original.Count; i++)
                {
                    Asn1Encodable enc = original[i];
                    if (!timeStampToRemove.Contains(enc))
                    {
                        filtered.Add(original[i]);
                    }
                }
                SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation
                                                                                             , new BcCms.AttributeTable(filtered));
                toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded());
            }
            return(toTimestamp.ToByteArray());
        }
Пример #2
0
		private CmsSignedData(
			CmsSignedData c)
		{
			this.signedData = c.signedData;
			this.contentInfo = c.contentInfo;
			this.signedContent = c.signedContent;
			this.signerInfoStore = c.signerInfoStore;
		}
        /**
        * generate a signed object that for a CMS Signed Data
        * object  - if encapsulate is true a copy
        * of the message will be included in the signature. The content type
        * is set according to the OID represented by the string signedContentType.
        */
        public CmsSignedData Generate(
            string			signedContentType,
			// FIXME Avoid accessing more than once to support CmsProcessableInputStream
            CmsProcessable	content,
            bool			encapsulate)
        {
            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

			_digests.Clear(); // clear the current preserved digest state

			//
            // add the precalculated SignerInfo objects.
            //
            foreach (SignerInformation signer in _signers)
            {
				digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));

				// TODO Verify the content type and calculated digest match the precalculated SignerInfo
				signerInfos.Add(signer.ToSignerInfo());
            }

			//
            // add the SignerInfo objects
            //
            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ?   null
				:	new DerObjectIdentifier(signedContentType);

            foreach (SignerInf signer in signerInfs)
            {
				try
                {
					digestAlgs.Add(signer.DigestAlgorithmID);
                    signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
				}
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for signature.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsException("error creating signature.", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new CmsException("error creating sid.", e);
                }
            }

			Asn1Set certificates = null;

			if (_certs.Count != 0)
			{
				certificates = CmsUtilities.CreateBerSetFromList(_certs);
			}

			Asn1Set certrevlist = null;

			if (_crls.Count != 0)
			{
				certrevlist = CmsUtilities.CreateBerSetFromList(_crls);
			}

			Asn1OctetString octs = null;
			if (encapsulate)
            {
                MemoryStream bOut = new MemoryStream();
				if (content != null)
				{
	                try
	                {
	                    content.Write(bOut);
	                }
	                catch (IOException e)
	                {
	                    throw new CmsException("encapsulation error.", e);
	                }
				}
				octs = new BerOctetString(bOut.ToArray());
            }

            ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);

            return new CmsSignedData(content, contentInfo);
        }
Пример #4
0
        private void pkcs7Test()
        {
            Asn1Encodable rootCert = Asn1Object.FromByteArray(CertPathTest.rootCertBin);
            Asn1Encodable rootCrl = Asn1Object.FromByteArray(CertPathTest.rootCrlBin);

            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser crlParser = new X509CrlParser();

            SignedData sigData = new SignedData(
                DerSet.Empty,
                new ContentInfo(CmsObjectIdentifiers.Data, null),
                new DerSet(
                    rootCert,
                    new DerTaggedObject(false, 2, Asn1Object.FromByteArray(AttrCertTest.attrCert))),
                new DerSet(rootCrl),
                DerSet.Empty);

            ContentInfo info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            X509Certificate cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert == null || !AreEqual(cert.GetEncoded(), rootCert.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 cert not read");
            }
            X509Crl crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl == null || !AreEqual(crl.GetEncoded(), rootCrl.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 crl not read");
            }
            ArrayList col = new ArrayList(certParser.ReadCertificates(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(cert))
            {
                Fail("PKCS7 cert collection not right");
            }
            col = new ArrayList(crlParser.ReadCrls(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(crl))
            {
                Fail("PKCS7 crl collection not right");
            }

            // data with no certificates or CRLs

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), DerSet.Empty, DerSet.Empty, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            // data with absent certificates and CRLS

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), null, null, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            //
            // sample message
            //
            ICollection certCol = certParser.ReadCertificates(pkcs7CrlProblem);
            ICollection crlCol = crlParser.ReadCrls(pkcs7CrlProblem);

            if (crlCol.Count != 0)
            {
                Fail("wrong number of CRLs: " + crlCol.Count);
            }

            if (certCol.Count != 4)
            {
                Fail("wrong number of Certs: " + certCol.Count);
            }
        }
Пример #5
0
        /// <summary>
        /// Constructs a new EF_SOD file.
        /// </summary>
        /// <param name="data">bytes of the EF_DG1 file</param>
        public SODFile(byte[] data)
        {
            MemoryStream dataStream = new MemoryStream(data);
            BERTLVInputStream tlvStream = new BERTLVInputStream(dataStream);
            int tag = tlvStream.readTag();
            if (tag != IDGFile.EF_SOD_TAG) throw new ArgumentException("Expected EF_SOD_TAG");
            int length = tlvStream.readLength();

            Asn1InputStream sodAsn1 = new Asn1InputStream(dataStream);
            DerSequence seq = (DerSequence)sodAsn1.ReadObject();
            DerObjectIdentifier objectIdentifier = (DerObjectIdentifier)seq[0];

            //DerTaggedObject o = (DerTaggedObject)seq[1];
            DerSequence s2 = (DerSequence)((DerTaggedObject)seq[1]).GetObject();
            IEnumerator e = s2.GetEnumerator();
            e.MoveNext();
            DerInteger version = (DerInteger)e.Current;
            e.MoveNext();
            Asn1Set digestAlgorithms = (Asn1Set)e.Current;
            e.MoveNext();
            ContentInfo contentInfo = ContentInfo.GetInstance(e.Current);

            Asn1Set signerInfos = null;
            bool certsBer = false;
            bool crlsBer = false;
            Asn1Set certificates = null;
            Asn1Set crls = null;

            while (e.MoveNext())
            {
                Object o = e.Current;
                if (o is Asn1TaggedObject)
                {
                    Asn1TaggedObject tagged = (Asn1TaggedObject)o;
                    switch (tagged.TagNo)
                    {
                        case 0:
                            certsBer = tagged is BerTaggedObject;
                            certificates = Asn1Set.GetInstance(tagged, false);
                            break;
                        case 1:
                            crlsBer = tagged is BerTaggedObject;
                            crls = Asn1Set.GetInstance(tagged, false);
                            break;
                        default:
                            throw new ArgumentException("unknown tag value " + tagged.TagNo);
                    }
                }
                else
                {
                    signerInfos = (Asn1Set)o;
                }
            }
            _signedData = new SignedData(digestAlgorithms, contentInfo, certificates, crls, signerInfos);
            byte[] content = ((DerOctetString)contentInfo.Content).GetOctets();
            Asn1InputStream inStream = new Asn1InputStream(content);
            _lds = new LdsSecurityObject((Asn1Sequence)inStream.ReadObject());
        }
Пример #6
0
        /**
         * generate a signed object that for a CMS Signed Data
         * object  - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         */
        public CmsSignedData Generate(
            string signedContentType,
            // FIXME Avoid accessing more than once to support CmsProcessableInputStream
            CmsProcessable content,
            bool encapsulate)
        {
            Asn1EncodableVector digestAlgs  = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

            _digests.Clear();             // clear the current preserved digest state

            //
            // add the precalculated SignerInfo objects.
            //
            foreach (SignerInformation signer in _signers)
            {
                digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));

                // TODO Verify the content type and calculated digest match the precalculated SignerInfo
                signerInfos.Add(signer.ToSignerInfo());
            }

            //
            // add the SignerInfo objects
            //
            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ?   null
                                :       new DerObjectIdentifier(signedContentType);

            foreach (SignerInf signer in signerInfs)
            {
                try
                {
                    digestAlgs.Add(signer.DigestAlgorithmID);
                    signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
                }
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for signature.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsException("error creating signature.", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new CmsException("error creating sid.", e);
                }
            }

            Asn1Set certificates = null;

            if (_certs.Count != 0)
            {
                certificates = UseDerForCerts
                    ?   CmsUtilities.CreateDerSetFromList(_certs)
                    :   CmsUtilities.CreateBerSetFromList(_certs);
            }

            Asn1Set certrevlist = null;

            if (_crls.Count != 0)
            {
                certrevlist = UseDerForCrls
                    ?   CmsUtilities.CreateDerSetFromList(_crls)
                    :   CmsUtilities.CreateBerSetFromList(_crls);
            }

            Asn1OctetString octs = null;

            if (encapsulate)
            {
                MemoryStream bOut = new MemoryStream();
                if (content != null)
                {
                    try
                    {
                        content.Write(bOut);
                    }
                    catch (IOException e)
                    {
                        throw new CmsException("encapsulation error.", e);
                    }
                }
                octs = new DerOctetString(bOut.ToArray());
            }

            ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);

            return(new CmsSignedData(content, contentInfo));
        }
Пример #7
0
		public CmsSignedData(
			ContentInfo sigData)
		{
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);

			//
			// this can happen if the signed message is sent simply to send a
			// certificate chain.
			//
			if (signedData.EncapContentInfo.Content != null)
			{
				this.signedContent = new CmsProcessableByteArray(
					((Asn1OctetString)(signedData.EncapContentInfo.Content)).GetOctets());
			}
//			else
//			{
//				this.signedContent = null;
//			}
		}
Пример #8
0
		public CmsSignedData(
			IDictionary	hashes,
			ContentInfo	sigData)
		{
			this.hashes = hashes;
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);
		}
Пример #9
0
		public CmsSignedData(
			CmsProcessable  signedContent,
			ContentInfo     sigData)
		{
			this.signedContent = signedContent;
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);
		}
Пример #10
0
		private ITestResult SignedTest()
		{
			try
			{
				ContentInfo info = ContentInfo.GetInstance(
					Asn1Object.FromByteArray(signedData));
				SignedData sData = SignedData.GetInstance(info.Content);

				sData = new SignedData(sData.DigestAlgorithms, sData.EncapContentInfo, sData.Certificates, sData.CRLs, sData.SignerInfos);
				info = new ContentInfo(CmsObjectIdentifiers.SignedData, sData);

				if (!Arrays.AreEqual(info.GetEncoded(), signedData))
				{
					return new SimpleTestResult(false, Name + ": CMS signed failed to re-encode");
				}

				return new SimpleTestResult(true, Name + ": Okay");
			}
			catch (Exception e)
			{
				return new SimpleTestResult(false, Name + ": CMS signed failed - " + e.ToString(), e);
			}
		}
        /// <summary>
        /// Generates PKCS#7 signature of specified data
        /// </summary>
        /// <param name="data">Data to be signed</param>
        /// <param name="detached">Flag indicating whether detached signature should be produced</param>
        /// <param name="signingCertificate">Signing certificate</param>
        /// <param name="certPath">Certification path for signing certificate</param>
        /// <returns>DER encoded PKCS#7 signature of specified data</returns>
        public byte[] GenerateSignature(byte[] data, bool detached, BCX509.X509Certificate signingCertificate, ICollection<BCX509.X509Certificate> certPath)
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            string hashOid = GetHashOid(_hashAlgorihtm);
            IDigest hashGenerator = GetHashGenerator(_hashAlgorihtm);

            // Compute hash of input data
            byte[] dataHash = ComputeDigest(hashGenerator, data);

            // Construct SignerInfo.signedAttrs
            Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(OID.PKCS9AtContentType),
                    new DerSet(new DerObjectIdentifier(OID.PKCS7IdData))));

            // Add PKCS#9 messageDigest signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(OID.PKCS9AtMessageDigest),
                    new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(OID.PKCS9AtSigningTime),
                    new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

            DerSet signedAttributes = new DerSet(signedAttributesVector);

            // Sign SignerInfo.signedAttrs with PKCS#1 v1.5 RSA signature using private key stored on PKCS#11 compatible device
            byte[] pkcs1Digest = ComputeDigest(hashGenerator, signedAttributes.GetDerEncoded());
            byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, hashOid);
            byte[] pkcs1Signature = null;

            using (Session session = _slot.OpenSession(true))
            using (Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS))
                pkcs1Signature = session.Sign(mechanism, _privateKeyHandle, pkcs1DigestInfo);

            // Construct SignerInfo
            SignerInfo signerInfo = new SignerInfo(
                new SignerIdentifier(new IssuerAndSerialNumber(signingCertificate.IssuerDN, signingCertificate.SerialNumber)),
                new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null),
                signedAttributes,
                new AlgorithmIdentifier(new DerObjectIdentifier(OID.PKCS1RsaEncryption), null),
                new DerOctetString(pkcs1Signature),
                null);

            // Construct SignedData.digestAlgorithms
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();
            digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                new DerObjectIdentifier(OID.PKCS7IdData),
                (detached) ? null : new DerOctetString(data));

            // Construct SignedData.certificates
            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();
            foreach (BCX509.X509Certificate cert in certPath)
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();
            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                new DerSet(digestAlgorithmsVector),
                encapContentInfo,
                new BerSet(certificatesVector),
                null,
                new DerSet(signerInfosVector));

            // Construct top level ContentInfo
            ContentInfo contentInfo = new ContentInfo(
                new DerObjectIdentifier(OID.PKCS7IdSignedData),
                signedData);

            return contentInfo.GetDerEncoded();
        }
Пример #12
0
        //var bcCert = CertificateUtilities.BuildBouncyCastleCollection(signingCertificates);
        //ICollection<Org.BouncyCastle.X509.X509Certificate>

        private SignedData CreateSignature(
            Session session,
            byte[] content,
            X509Certificate2Collection signingCertificates)
        {
            var digestOid     = ToDigestAlgorithmOid(DigestAlgorithm).Value;
            var hashGenerator = GetHashGenerator(DigestAlgorithm);
            var dataHash      = ComputeDigest(hashGenerator, content);

            // Construct SignerInfo.signedAttrs
            var signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute as Data
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtContentType.Id),
                    new DerSet(new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id))));

            // Add PKCS#9 messageDigest signed attribute with hash der string encoded
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtMessageDigest.Id),
                    new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtSigningTime.Id),
                    new DerSet(new Time(new DerUtcTime(DateTime.UtcNow)))));

            var signedAttributes = new DerSet(signedAttributesVector);



            // Sign SignerInfo.signedAttrs with PKCS#1 v1.5 RSA signature using private key stored on PKCS#11 compatible device
            byte[] pkcs1Digest     = ComputeDigest(hashGenerator, signedAttributes.GetDerEncoded());
            byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, digestOid);

            // Construct SignedData.digestAlgorithms
            var digestAlgorithmsVector = new Asn1EncodableVector();
            // Construct SignedData.certificates
            var certificatesVector = new Asn1EncodableVector();
            // Construct SignedData.signerInfos
            var signerInfosVector = new Asn1EncodableVector();

            // Construct SignedData.encapContentInfo
            var encapContentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(
                new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id),
                null); //Always a detached signature.


            foreach (var signingCertificate in signingCertificates)
            {
                var bcSigningCertificate = CertificateUtilities.ToBouncyCastleObject(signingCertificate.RawData);
                // Get public key from certificate
                var pubKeyParams = bcSigningCertificate.GetPublicKey(); //AsymmetricKeyParameter
                if (!(pubKeyParams is RsaKeyParameters))
                {
                    throw new NotSupportedException("Unsupported keys.  Currently supporting RSA keys only.");
                }

                var rsaPubKeyParams = (RsaKeyParameters)pubKeyParams;

                byte[] pkcs1Signature;

                if (signingCertificate.HasPrivateKey)
                {
                    pkcs1Signature = GeneratePkcs1Signature(signingCertificate, pkcs1DigestInfo);
                }
                else
                {
                    pkcs1Signature = GeneratePkcs1Signature(session, rsaPubKeyParams, bcSigningCertificate, pkcs1DigestInfo);
                }

                // Construct SignerInfo
                var signerInfo = new Org.BouncyCastle.Asn1.Cms.SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcSigningCertificate.IssuerDN, bcSigningCertificate.SerialNumber)),
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null),
                    signedAttributes,
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(PkcsObjectIdentifiers.RsaEncryption.Id), null),
                    new DerOctetString(pkcs1Signature),
                    null);

                digestAlgorithmsVector.Add(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null));
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(bcSigningCertificate.GetEncoded())));
                signerInfosVector.Add(signerInfo.ToAsn1Object());
            }

            // Construct SignedData
            var signedData = new SignedData(
                new DerSet(digestAlgorithmsVector),
                encapContentInfo,
                new BerSet(certificatesVector),
                null,
                new DerSet(signerInfosVector));

            return(signedData);
        }