示例#1
0
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            if (si is null)
            {
                throw new System.ArgumentNullException(nameof(si));
            }

            if (SignatureTsa == null)
            {
                throw new System.ArgumentNullException(nameof(SignatureTsa));
            }
            logger.Info("Extend signature with id " + si.SignerID);
            BcCms.AttributeTable unsigned = si.UnsignedAttributes;
            IDictionary          unsignedAttrHash;

            if (unsigned is null)
            {
                unsignedAttrHash = new Dictionary <DerObjectIdentifier, Attribute>();
            }
            else
            {
                unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            }

            //TODO: jbonilla - What happens if it is already CAdES-T? It should not be extended again.
            Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, SignatureTsa, si.GetSignature());

            unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp);
            SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable
                                                                                      (unsignedAttrHash));

            return(newsi);
        }
        public static SignerInformation AddCounterSigners(SignerInformation signerInformation, SignerInformationStore counterSigners)
        {
            Org.BouncyCastle.Asn1.Cms.SignerInfo     signerInfo         = signerInformation.info;
            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInformation.UnsignedAttributes;
            Asn1EncodableVector asn1EncodableVector  = ((unsignedAttributes == null) ? new Asn1EncodableVector() : unsignedAttributes.ToAsn1EncodableVector());
            Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)counterSigners.GetSigners()).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    SignerInformation signerInformation2 = (SignerInformation)enumerator.get_Current();
                    asn1EncodableVector2.Add(signerInformation2.ToSignerInfo());
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            asn1EncodableVector.Add(new Attribute(CmsAttributes.CounterSignature, new DerSet(asn1EncodableVector2)));
            return(new SignerInformation(new Org.BouncyCastle.Asn1.Cms.SignerInfo(signerInfo.SignerID, signerInfo.DigestAlgorithm, signerInfo.AuthenticatedAttributes, signerInfo.DigestEncryptionAlgorithm, signerInfo.EncryptedDigest, new DerSet(asn1EncodableVector)), signerInformation.contentType, signerInformation.content, null));
        }
        private Asn1Object GetSingleValuedSignedAttribute(DerObjectIdentifier attrOID, string printableName)
        {
            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = this.UnsignedAttributes;
            if (unsignedAttributes != null && unsignedAttributes.GetAll(attrOID).Count > 0)
            {
                throw new CmsException("The " + printableName + " attribute MUST NOT be an unsigned attribute");
            }
            Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttributes = this.SignedAttributes;
            if (signedAttributes == null)
            {
                return(null);
            }
            Asn1EncodableVector all = signedAttributes.GetAll(attrOID);

            switch (all.Count)
            {
            case 0:
                return(null);

            case 1:
            {
                Org.BouncyCastle.Asn1.Cms.Attribute attribute = (Org.BouncyCastle.Asn1.Cms.Attribute)all[0];
                Asn1Set attrValues = attribute.AttrValues;
                if (attrValues.Count != 1)
                {
                    throw new CmsException("A " + printableName + " attribute MUST have a single attribute value");
                }
                return(attrValues[0].ToAsn1Object());
            }

            default:
                throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " + printableName + " attribute");
            }
        }
        public static SignerInformation AddCounterSigners(SignerInformation signerInformation, SignerInformationStore counterSigners)
        {
            Org.BouncyCastle.Asn1.Cms.SignerInfo     signerInfo         = signerInformation.info;
            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInformation.UnsignedAttributes;
            Asn1EncodableVector asn1EncodableVector;

            if (unsignedAttributes != null)
            {
                asn1EncodableVector = unsignedAttributes.ToAsn1EncodableVector();
            }
            else
            {
                asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]);
            }
            Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]);

            foreach (SignerInformation signerInformation2 in counterSigners.GetSigners())
            {
                asn1EncodableVector2.Add(new Asn1Encodable[]
                {
                    signerInformation2.ToSignerInfo()
                });
            }
            asn1EncodableVector.Add(new Asn1Encodable[]
            {
                new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(asn1EncodableVector2))
            });
            return(new SignerInformation(new Org.BouncyCastle.Asn1.Cms.SignerInfo(signerInfo.SignerID, signerInfo.DigestAlgorithm, signerInfo.AuthenticatedAttributes, signerInfo.DigestEncryptionAlgorithm, signerInfo.EncryptedDigest, new DerSet(asn1EncodableVector)), signerInformation.contentType, signerInformation.content, null));
        }
示例#5
0
        /// <exception cref="System.IO.IOException"></exception>
        protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData
                                                                         , SignerInformation si, SignatureParameters parameters, Document originalData)
        {
            if (this.signatureTsa == null)
            {
                throw new ConfigurationException(ConfigurationException.MSG.CONFIGURE_TSP_SERVER);
            }
            //LOG.Info("Extend signature with id " + si.SignerID);
            BcCms.AttributeTable unsigned = si.UnsignedAttributes;
            //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = null;
            IDictionary unsignedAttrHash = null;

            if (unsigned == null)
            {
                unsignedAttrHash = new Dictionary <DerObjectIdentifier, Attribute>();
            }
            else
            {
                unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            }

            //TODO jbonilla - ¿Qué ocurre si ya es CAdES-T? No se debería volver a extender.
            Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken
                                                                 , this.signatureTsa, digestAlgorithm, si.GetSignature());

            //unsignedAttrHash.Put(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp);
            unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp);
            SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable
                                                                                      (unsignedAttrHash));

            return(newsi);
        }
示例#6
0
        public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;
            TspUtil.ValidateCertificate(cert);
            IDictionary dictionary;

            if (signedAttr != null)
            {
                dictionary = signedAttr.ToDictionary();
            }
            else
            {
                dictionary = Platform.CreateHashtable();
            }
            try
            {
                byte[]    hash      = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
                EssCertID essCertID = new EssCertID(hash);
                Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertID)));
                dictionary[attribute.AttrType] = attribute;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e2)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e2);
            }
            this.signedAttr = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
        }
示例#7
0
        public AttributeTable Remove(DerObjectIdentifier attrType)
        {
            AttributeTable attributeTable = new AttributeTable(this.attributes);

            attributeTable.attributes.Remove(attrType);
            return(attributeTable);
        }
示例#8
0
        public AttributeTable Add(DerObjectIdentifier attrType, Asn1Encodable attrValue)
        {
            AttributeTable attributeTable = new AttributeTable(this.attributes);

            attributeTable.AddAttribute(new Attribute(attrType, new DerSet(attrValue)));
            return(attributeTable);
        }
 protected internal virtual Asn1Set GetAttributeSet(Org.BouncyCastle.Asn1.Cms.AttributeTable attr)
 {
     if (attr != null)
     {
         return(new DerSet(attr.ToAsn1EncodableVector()));
     }
     return(null);
 }
示例#10
0
            internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
            {
                //IL_00bf: Unknown result type (might be due to invalid IL or missing references)
                //IL_00c6: Expected O, but got Unknown
                AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID;
                string digestAlgName = Helper.GetDigestAlgName(digestOID);
                string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

                byte[] array;
                if (outer._digests.Contains((object)digestOID))
                {
                    array = (byte[])outer._digests.get_Item((object)digestOID);
                }
                else
                {
                    IDigest digestInstance = Helper.GetDigestInstance(digestAlgName);
                    content?.Write((Stream)(object)new DigOutputStream(digestInstance));
                    array = DigestUtilities.DoFinal(digestInstance);
                    outer._digests.Add((object)digestOID, ((global::System.Array)array).Clone());
                }
                IStreamCalculator streamCalculator = sigCalc.CreateCalculator();
                Stream            val     = (Stream) new BufferedStream(streamCalculator.Stream);
                Asn1Set           asn1Set = null;

                if (sAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters);
                    if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                    {
                        IDictionary val2 = attributeTable.ToDictionary();
                        val2.Remove((object)CmsAttributes.ContentType);
                        attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(val2);
                    }
                    asn1Set = outer.GetAttributeSet(attributeTable);
                    new DerOutputStream(val).WriteObject(asn1Set);
                }
                else
                {
                    content?.Write(val);
                }
                Platform.Dispose(val);
                byte[]  array2 = ((IBlockResult)streamCalculator.GetResult()).Collect();
                Asn1Set unauthenticatedAttributes = null;

                if (unsAttr != null)
                {
                    IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    baseParameters2.set_Item((object)CmsAttributeTableParameter.Signature, ((global::System.Array)array2).Clone());
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2);
                    unauthenticatedAttributes = outer.GetAttributeSet(attributes);
                }
                Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters);

                return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
            }
示例#11
0
 /**
  * add a signer with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param cert certificate containing corresponding public key
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     X509Certificate cert,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID,
               signedAttr, unsignedAttr);
 }
        internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
        {
            AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID;
            string digestAlgName = Helper.GetDigestAlgName(digestOID);
            string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

            byte[] array;
            if (outer._digests.Contains(digestOID))
            {
                array = (byte[])outer._digests[digestOID];
            }
            else
            {
                IDigest digestInstance = Helper.GetDigestInstance(digestAlgName);
                content?.Write(new DigOutputStream(digestInstance));
                array = DigestUtilities.DoFinal(digestInstance);
                outer._digests.Add(digestOID, array.Clone());
            }
            IStreamCalculator streamCalculator = sigCalc.CreateCalculator();
            Stream            stream           = new BufferedStream(streamCalculator.Stream);
            Asn1Set           asn1Set          = null;

            if (sAttr != null)
            {
                IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters);
                if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                {
                    IDictionary dictionary = attributeTable.ToDictionary();
                    dictionary.Remove(CmsAttributes.ContentType);
                    attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                }
                asn1Set = outer.GetAttributeSet(attributeTable);
                new DerOutputStream(stream).WriteObject(asn1Set);
            }
            else
            {
                content?.Write(stream);
            }
            Platform.Dispose(stream);
            byte[]  array2 = ((IBlockResult)streamCalculator.GetResult()).Collect();
            Asn1Set unauthenticatedAttributes = null;

            if (unsAttr != null)
            {
                IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2);
                unauthenticatedAttributes = outer.GetAttributeSet(attributes);
            }
            Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
            AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters);

            return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
        }
示例#13
0
 /**
  * add a signer with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param subjectKeyID subjectKeyID of corresponding public key
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     byte[] subjectKeyID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     AddSigner(privateKey, subjectKeyID, digestOID, GetEncOid(privateKey, digestOID),
               new DefaultSignedAttributeTableGenerator(signedAttr),
               new SimpleAttributeTableGenerator(unsignedAttr));
 }
示例#14
0
 public void MyAddSigner(
     NetCrypto.RSACryptoServiceProvider crProv,
     X509Certificate cert,
     string encryptionOID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     signerInfs.Add(new SignerInf(this, crProv, null, GetSignerIdentifier(cert), digestOID, encryptionOID,
                                  new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr), null));
 }
示例#15
0
 internal SignerInf(CmsSignedGenerator outer, ISignatureFactory sigCalc, SignerIdentifier signerIdentifier, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer            = outer;
     this.sigCalc          = sigCalc;
     this.signerIdentifier = signerIdentifier;
     digestOID             = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     encOID               = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.sAttr           = sAttr;
     this.unsAttr         = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
 internal SignerInf(CmsSignedGenerator outer, AsymmetricKeyParameter key, SignerIdentifier signerIdentifier, string digestOID, string encOID, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer            = outer;
     this.key              = key;
     this.signerIdentifier = signerIdentifier;
     this.digestOID        = digestOID;
     this.encOID           = encOID;
     this.sAttr            = sAttr;
     this.unsAttr          = unsAttr;
     this.baseSignedTable  = baseSignedTable;
 }
 /**
  * Initialise with some extra attributes or overrides.
  *
  * @param attributeTable initial attribute table to use.
  */
 public DefaultSignedAttributeTableGenerator(
     AttributeTable attributeTable)
 {
     if (attributeTable != null)
     {
         table = attributeTable.ToDictionary();
     }
     else
     {
         table = Platform.CreateHashtable();
     }
 }
		/**
		 * Initialise with some extra attributes or overrides.
		 *
		 * @param attributeTable initial attribute table to use.
		 */
		public DefaultSignedAttributeTableGenerator(
			AttributeTable attributeTable)
		{
			if (attributeTable != null)
			{
				table = attributeTable.ToHashtable();
			}
			else
			{
				table = new Hashtable();
			}
		}
		/**
		 * Initialise with some extra attributes or overrides.
		 *
		 * @param attributeTable initial attribute table to use.
		 */
		public DefaultSignedAttributeTableGenerator(
			AttributeTable attributeTable)
		{
			if (attributeTable != null)
			{
				table = attributeTable.ToDictionary();
			}
			else
			{
				table = Platform.CreateHashtable();
			}
		}
            public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest)
            {
                SignerInfo result;

                try
                {
                    string  digestAlgName = CmsSignedDataStreamGenerator.Helper.GetDigestAlgName(this._digestOID);
                    string  algorithm     = digestAlgName + "with" + this._encName;
                    byte[]  array         = calculatedDigest;
                    Asn1Set asn1Set       = null;
                    if (this._sAttr != null)
                    {
                        IDictionary baseParameters = this.outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
                        Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = this._sAttr.GetAttributes(baseParameters);
                        if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                        {
                            IDictionary dictionary = attributeTable.ToDictionary();
                            dictionary.Remove(CmsAttributes.ContentType);
                            attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                        }
                        asn1Set = this.outer.GetAttributeSet(attributeTable);
                        array   = asn1Set.GetEncoded("DER");
                    }
                    else if (this._encName.Equals("RSA"))
                    {
                        DigestInfo digestInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
                        array = digestInfo.GetEncoded("DER");
                    }
                    this._sig.BlockUpdate(array, 0, array.Length);
                    byte[]  array2 = this._sig.GenerateSignature();
                    Asn1Set unauthenticatedAttributes = null;
                    if (this._unsAttr != null)
                    {
                        IDictionary baseParameters2 = this.outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
                        baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                        Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this._unsAttr.GetAttributes(baseParameters2);
                        unauthenticatedAttributes = this.outer.GetAttributeSet(attributes);
                    }
                    Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                    AlgorithmIdentifier encAlgorithmIdentifier = CmsSignedGenerator.GetEncAlgorithmIdentifier(new DerObjectIdentifier(this._encOID), defaultX509Parameters);
                    result = new SignerInfo(this._signerIdentifier, digestAlgorithm, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes);
                }
                catch (IOException e)
                {
                    throw new CmsStreamException("encoding error.", e);
                }
                catch (SignatureException e2)
                {
                    throw new CmsStreamException("error creating signature.", e2);
                }
                return(result);
            }
示例#21
0
        public SignerInformationStore GetCounterSignatures()
        {
            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = UnsignedAttributes;
            if (unsignedAttributes == null)
            {
                return(new SignerInformationStore((global::System.Collections.ICollection)Platform.CreateArrayList(0)));
            }
            global::System.Collections.IList list = Platform.CreateArrayList();
            Asn1EncodableVector all = unsignedAttributes.GetAll(CmsAttributes.CounterSignature);

            global::System.Collections.IEnumerator enumerator = all.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    Attribute attribute  = (Attribute)enumerator.get_Current();
                    Asn1Set   attrValues = attribute.AttrValues;
                    _ = attrValues.Count;
                    _ = 1;
                    {
                        global::System.Collections.IEnumerator enumerator2 = attrValues.GetEnumerator();
                        try
                        {
                            while (enumerator2.MoveNext())
                            {
                                Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator2.get_Current();
                                Org.BouncyCastle.Asn1.Cms.SignerInfo instance = Org.BouncyCastle.Asn1.Cms.SignerInfo.GetInstance(asn1Encodable.ToAsn1Object());
                                string digestAlgName = CmsSignedHelper.Instance.GetDigestAlgName(instance.DigestAlgorithm.Algorithm.Id);
                                list.Add((object)new SignerInformation(instance, null, null, new CounterSignatureDigestCalculator(digestAlgName, GetSignature())));
                            }
                        }
                        finally
                        {
                            global::System.IDisposable disposable2 = enumerator2 as global::System.IDisposable;
                            if (disposable2 != null)
                            {
                                disposable2.Dispose();
                            }
                        }
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(new SignerInformationStore((global::System.Collections.ICollection)list));
        }
            internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
            {
                AlgorithmIdentifier digestAlgorithmID = this.DigestAlgorithmID;
                string  digestAlgName     = CmsSignedDataGenerator.Helper.GetDigestAlgName(this.digestOID);
                IDigest digestInstance    = CmsSignedDataGenerator.Helper.GetDigestInstance(digestAlgName);
                string  algorithm         = digestAlgName + "with" + CmsSignedDataGenerator.Helper.GetEncryptionAlgName(this.encOID);
                ISigner signatureInstance = CmsSignedDataGenerator.Helper.GetSignatureInstance(algorithm);

                if (content != null)
                {
                    content.Write(new DigOutputStream(digestInstance));
                }
                byte[] array = DigestUtilities.DoFinal(digestInstance);
                this.outer._digests.Add(this.digestOID, array.Clone());
                signatureInstance.Init(true, new ParametersWithRandom(this.key, random));
                Stream  stream  = new BufferedStream(new SigOutputStream(signatureInstance));
                Asn1Set asn1Set = null;

                if (this.sAttr != null)
                {
                    IDictionary baseParameters = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = this.sAttr.GetAttributes(baseParameters);
                    if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                    {
                        IDictionary dictionary = attributeTable.ToDictionary();
                        dictionary.Remove(CmsAttributes.ContentType);
                        attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                    }
                    asn1Set = this.outer.GetAttributeSet(attributeTable);
                    new DerOutputStream(stream).WriteObject(asn1Set);
                }
                else if (content != null)
                {
                    content.Write(stream);
                }
                stream.Close();
                byte[]  array2 = signatureInstance.GenerateSignature();
                Asn1Set unauthenticatedAttributes = null;

                if (this.unsAttr != null)
                {
                    IDictionary baseParameters2 = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this.unsAttr.GetAttributes(baseParameters2);
                    unauthenticatedAttributes = this.outer.GetAttributeSet(attributes);
                }
                Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                AlgorithmIdentifier encAlgorithmIdentifier = CmsSignedGenerator.GetEncAlgorithmIdentifier(new DerObjectIdentifier(this.encOID), defaultX509Parameters);

                return(new SignerInfo(this.signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
            }
 public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest)
 {
     //IL_016e: Expected O, but got Unknown
     try
     {
         string  digestAlgName = Helper.GetDigestAlgName(_digestOID);
         string  algorithm     = digestAlgName + "with" + _encName;
         byte[]  array         = calculatedDigest;
         Asn1Set asn1Set       = null;
         if (_sAttr != null)
         {
             IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
             Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = _sAttr.GetAttributes(baseParameters);
             if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
             {
                 IDictionary val = attributeTable.ToDictionary();
                 val.Remove((object)CmsAttributes.ContentType);
                 attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(val);
             }
             asn1Set = outer.GetAttributeSet(attributeTable);
             array   = asn1Set.GetEncoded("DER");
         }
         else if (_encName.Equals("RSA"))
         {
             DigestInfo digestInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
             array = digestInfo.GetEncoded("DER");
         }
         _sig.BlockUpdate(array, 0, array.Length);
         byte[]  array2 = _sig.GenerateSignature();
         Asn1Set unauthenticatedAttributes = null;
         if (_unsAttr != null)
         {
             IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
             baseParameters2.set_Item((object)CmsAttributeTableParameter.Signature, ((global::System.Array)array2).Clone());
             Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = _unsAttr.GetAttributes(baseParameters2);
             unauthenticatedAttributes = outer.GetAttributeSet(attributes);
         }
         Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
         AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(_encOID), defaultX509Parameters);
         return(new SignerInfo(_signerIdentifier, digestAlgorithm, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
     }
     catch (IOException val2)
     {
         IOException e = val2;
         throw new CmsStreamException("encoding error.", (global::System.Exception)(object) e);
     }
     catch (SignatureException e2)
     {
         throw new CmsStreamException("error creating signature.", e2);
     }
 }
 public override void Close()
 {
     this._out.Close();
     this._eiGen.Close();
     if (this._outer.unprotectedAttributeGenerator != null)
     {
         Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this._outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
         Asn1Set obj = new BerSet(attributes.ToAsn1EncodableVector());
         this._envGen.AddObject(new DerTaggedObject(false, 1, obj));
     }
     this._envGen.Close();
     this._cGen.Close();
     base.Close();
 }
示例#25
0
            internal SignerInf(CmsSignedGenerator outer, AsymmetricKeyParameter key, SignerIdentifier signerIdentifier, string digestOID, string encOID, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable baseSignedTable)
            {
                string digestAlgName = Helper.GetDigestAlgName(digestOID);
                string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

                this.outer            = outer;
                sigCalc               = new Asn1SignatureFactory(algorithm, key);
                this.signerIdentifier = signerIdentifier;
                this.digestOID        = digestOID;
                this.encOID           = encOID;
                this.sAttr            = sAttr;
                this.unsAttr          = unsAttr;
                this.baseSignedTable  = baseSignedTable;
            }
 public override void Close()
 {
     Platform.Dispose((Stream)(object)_out);
     _eiGen.Close();
     if (_outer.unprotectedAttributeGenerator != null)
     {
         Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = _outer.unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
         Asn1Set obj = new BerSet(attributes.ToAsn1EncodableVector());
         _envGen.AddObject(new DerTaggedObject(explicitly: false, 1, obj));
     }
     _envGen.Close();
     _cGen.Close();
     base.Close();
 }
示例#27
0
 /**
  * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
  *
  * @param key signing key to use
  * @param subjectKeyID subjectKeyID of corresponding public key
  * @param encryptionOID digest encryption algorithm OID
  * @param digestOID digest algorithm OID
  * @param signedAttr table of attributes to be included in signature
  * @param unsignedAttr table of attributes to be included as unsigned
  */
 public void AddSigner(
     AsymmetricKeyParameter privateKey,
     byte[] subjectKeyID,
     string encryptionOID,
     string digestOID,
     Asn1.Cms.AttributeTable signedAttr,
     Asn1.Cms.AttributeTable unsignedAttr)
 {
     signerInfs.Add(new SignerInf(this, null, privateKey, GetSignerIdentifier(subjectKeyID),
                                  digestOID, encryptionOID,
                                  new DefaultSignedAttributeTableGenerator(signedAttr),
                                  new SimpleAttributeTableGenerator(unsignedAttr),
                                  signedAttr));
 }
示例#28
0
        private SignerInformation GetSignerInformation(SignerInfoNode signerInfoNode)
        {
            if (signerInfoNode.CounterSignatures.Count > 0)
            {
                var nodes = GetCounterSignatures(signerInfoNode);

                BcCms.AttributeTable attributes = signerInfoNode.SignerInformation.UnsignedAttributes.Remove(CmsAttributes.CounterSignature);

                SignerInformation newSignerInformation = SignerInformation.ReplaceUnsignedAttributes(signerInfoNode.SignerInformation, attributes);

                return(SignerInformation.AddCounterSigners(newSignerInformation, new SignerInformationStore(nodes.ToArray())));
            }
            else
            {
                return(signerInfoNode.SignerInformation);
            }
        }
 public Org.BouncyCastle.Asn1.Cms.AttributeTable GetUnauthAttrs()
 {
     if (unauthAttrs == null && unauthAttrNotRead)
     {
         Asn1SetParser asn1SetParser = authData.GetUnauthAttrs();
         unauthAttrNotRead = false;
         if (asn1SetParser != null)
         {
             Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();
             IAsn1Convertible    asn1Convertible;
             while ((asn1Convertible = asn1SetParser.ReadObject()) != null)
             {
                 Asn1SequenceParser asn1SequenceParser = (Asn1SequenceParser)asn1Convertible;
                 asn1EncodableVector.Add(asn1SequenceParser.ToAsn1Object());
             }
             unauthAttrs = new Org.BouncyCastle.Asn1.Cms.AttributeTable(new DerSet(asn1EncodableVector));
         }
     }
     return(unauthAttrs);
 }
 public Org.BouncyCastle.Asn1.Cms.AttributeTable GetUnprotectedAttributes()
 {
     if (_unprotectedAttributes == null && _attrNotRead)
     {
         Asn1SetParser unprotectedAttrs = envelopedData.GetUnprotectedAttrs();
         _attrNotRead = false;
         if (unprotectedAttrs != null)
         {
             Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();
             IAsn1Convertible    asn1Convertible;
             while ((asn1Convertible = unprotectedAttrs.ReadObject()) != null)
             {
                 Asn1SequenceParser asn1SequenceParser = (Asn1SequenceParser)asn1Convertible;
                 asn1EncodableVector.Add(asn1SequenceParser.ToAsn1Object());
             }
             _unprotectedAttributes = new Org.BouncyCastle.Asn1.Cms.AttributeTable(new DerSet(asn1EncodableVector));
         }
     }
     return(_unprotectedAttributes);
 }
示例#31
0
 /// <summary>
 /// Signer is received with crypto provider or pr. key (if the crypto provider == null)
 /// </summary>
 /// <param name="krProv">Crypto provider. if null than use key</param>
 /// <param name="key">Private key</param>
 internal SignerInf(
     CmsSignedGenerator outer,
     NetCrypto.RSACryptoServiceProvider krProv,
     AsymmetricKeyParameter key,
     SignerIdentifier signerIdentifier,
     string digestOID,
     string encOID,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer            = outer;
     this.key              = key;
     this.krProv           = krProv;
     this.signerIdentifier = signerIdentifier;
     this.digestOID        = digestOID;
     this.encOID           = encOID;
     this.sAttr            = sAttr;
     this.unsAttr          = unsAttr;
     this.baseSignedTable  = baseSignedTable;
 }
        public SignerInformationStore GetCounterSignatures()
        {
            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = this.UnsignedAttributes;
            if (unsignedAttributes == null)
            {
                return(new SignerInformationStore(Platform.CreateArrayList(0)));
            }
            IList list = Platform.CreateArrayList();
            Asn1EncodableVector all = unsignedAttributes.GetAll(CmsAttributes.CounterSignature);

            foreach (Org.BouncyCastle.Asn1.Cms.Attribute attribute in all)
            {
                Asn1Set attrValues = attribute.AttrValues;
                int     arg_53_0   = attrValues.Count;
                foreach (Asn1Encodable asn1Encodable in attrValues)
                {
                    Org.BouncyCastle.Asn1.Cms.SignerInfo instance = Org.BouncyCastle.Asn1.Cms.SignerInfo.GetInstance(asn1Encodable.ToAsn1Object());
                    string digestAlgName = CmsSignedHelper.Instance.GetDigestAlgName(instance.DigestAlgorithm.ObjectID.Id);
                    list.Add(new SignerInformation(instance, null, null, new CounterSignatureDigestCalculator(digestAlgName, this.GetSignature())));
                }
            }
            return(new SignerInformationStore(list));
        }
示例#33
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
		/// </summary>
		/// <remarks>
		/// <para>The initial value of the <see cref="DigestAlgorithm"/> will be set to
		/// <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
		/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties
		/// will be initialized to empty tables.</para>
		/// </remarks>
		CmsSigner ()
		{
			UnsignedAttributes = new AttributeTable (new Dictionary<DerObjectIdentifier, Asn1Encodable> ());
			SignedAttributes = new AttributeTable (new Dictionary<DerObjectIdentifier, Asn1Encodable> ());
			DigestAlgorithm = DigestAlgorithm.Sha1;
		}
示例#34
0
 /**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1.
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 */    
 public PdfPKCS7(byte[] contentsKey) {
     Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));
     
     //
     // Basic checks to make sure it's a PKCS#7 SignedData Object
     //
     Asn1Object pkcs;
     
     try {
         pkcs = din.ReadObject();
     }
     catch  {
         throw new ArgumentException("can't decode PKCS7SignedData object");
     }
     if (!(pkcs is Asn1Sequence)) {
         throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
     }
     Asn1Sequence signedData = (Asn1Sequence)pkcs;
     DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
     // the positions that we care are:
     //     0 - version
     //     1 - digestAlgorithms
     //     2 - possible ID_PKCS7_DATA
     //     (the certificates and crls are taken out by other means)
     //     last - signerInfos
     
     // the version
     version = ((DerInteger)content[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Hashtable();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new ArrayList();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new ArrayList();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
     // the positions that we care are
     //     0 - version
     //     1 - the signing certificate serial number
     //     2 - the digest algorithm
     //     3 or 4 - digestEncryptionAlgorithm
     //     4 or 5 - encryptedDigest
     signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo != 1)
                         continue;
                     Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                     FindOcsp(seqin);
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException("Authenticated attribute is missing the digest.");
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (RSAdata != null || digestAttr != null) {
         messageDigest = GetHashClass();
     }
     sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
     sig.Init(false, signCert.GetPublicKey());
 }
		public SimpleAttributeTableGenerator(
			AttributeTable attributes)
		{
			this.attributes = attributes;
		}
		public override void PerformTest()
        {
            Asn1EncodableVector v = new Asn1EncodableVector(
				new Asn1Cms.Attribute(type1, new DerSet(type1)),
				new Asn1Cms.Attribute(type2, new DerSet(type2)));

			Asn1Cms.AttributeTable table = new Asn1Cms.AttributeTable(v);

			Asn1Cms.Attribute a = table[type1];
            if (a == null)
            {
                Fail("type1 attribute not found.");
            }
            if (!a.AttrValues.Equals(new DerSet(type1)))
            {
                Fail("wrong value retrieved for type1!");
            }

			a = table[type2];
            if (a == null)
            {
                Fail("type2 attribute not found.");
            }
            if (!a.AttrValues.Equals(new DerSet(type2)))
            {
                Fail("wrong value retrieved for type2!");
            }

			a = table[type3];
            if (a != null)
            {
                Fail("type3 attribute found when none expected.");
            }

			Asn1EncodableVector vec = table.GetAll(type1);
            if (vec.Count != 1)
            {
                Fail("wrong vector size for type1.");
            }

			vec = table.GetAll(type3);
            if (vec.Count != 0)
            {
                Fail("wrong vector size for type3.");
            }

			vec = table.ToAsn1EncodableVector();
            if (vec.Count != 2)
            {
                Fail("wrong vector size for single.");
            }

            IDictionary t = table.ToDictionary();

			if (t.Count != 2)
            {
                Fail("hashtable wrong size.");
            }

            // multiple

			v = new Asn1EncodableVector(
				new Asn1Cms.Attribute(type1, new DerSet(type1)),
				new Asn1Cms.Attribute(type1, new DerSet(type2)),
				new Asn1Cms.Attribute(type1, new DerSet(type3)),
				new Asn1Cms.Attribute(type2, new DerSet(type2)));

			table = new Asn1Cms.AttributeTable(v);

			a = table[type1];
            if (!a.AttrValues.Equals(new DerSet(type1)))
            {
                Fail("wrong value retrieved for type1 multi Get!");
            }

			vec = table.GetAll(type1);
            if (vec.Count != 3)
            {
                Fail("wrong vector size for multiple type1.");
            }

			a = (Asn1Cms.Attribute)vec[0];
            if (!a.AttrValues.Equals(new DerSet(type1)))
            {
                Fail("wrong value retrieved for type1(0)!");
            }

            a = (Asn1Cms.Attribute)vec[1];
            if (!a.AttrValues.Equals(new DerSet(type2)))
            {
                Fail("wrong value retrieved for type1(1)!");
            }

            a = (Asn1Cms.Attribute)vec[2];
            if (!a.AttrValues.Equals(new DerSet(type3)))
            {
                Fail("wrong value retrieved for type1(2)!");
            }

            vec = table.GetAll(type2);
            if (vec.Count != 1)
            {
                Fail("wrong vector size for multiple type2.");
            }

            vec = table.ToAsn1EncodableVector();
            if (vec.Count != 4)
            {
                Fail("wrong vector size for multiple.");
            }
        }
示例#37
0
 public PdfPKCS7(byte[] contentsKey, bool tsp) {
     isTsp = tsp;
     Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));
     
     //
     // Basic checks to make sure it's a PKCS#7 SignedData Object
     //
     Asn1Object pkcs;
     
     try {
         pkcs = din.ReadObject();
     }
     catch  {
         throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
     }
     if (!(pkcs is Asn1Sequence)) {
         throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
     }
     Asn1Sequence signedData = (Asn1Sequence)pkcs;
     DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
     // the positions that we care are:
     //     0 - version
     //     1 - digestAlgorithms
     //     2 - possible ID_PKCS7_DATA
     //     (the certificates and crls are taken out by other means)
     //     last - signerInfos
     
     // the version
     version = ((DerInteger)content[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Dictionary<string,object>();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new List<X509Certificate>();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new List<X509Crl>();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
     // the positions that we care are
     //     0 - version
     //     1 - the signing certificate issuer and serial number
     //     2 - the digest algorithm
     //     3 or 4 - digestEncryptionAlgorithm
     //     4 or 5 - encryptedDigest
     signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1", 
             issuer.ToString() + " / " + serialNumber.ToString(16)));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo == 1) {
                         Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                         FindOcsp(seqin);
                     }
                     if (tg.TagNo == 0) {
                         Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                         FindCRL(seqin);
                     }
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null && ts.AttrValues.Count > 0) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (isTsp) {
         Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData);
         this.timeStampToken = new TimeStampToken(contentInfoTsp);
         TimeStampTokenInfo info = timeStampToken.TimeStampInfo;
         String algOID = info.MessageImprintAlgOid;
         messageDigest = DigestUtilities.GetDigest(algOID);
     }
     else {
         if (RSAdata != null || digestAttr != null) {
             messageDigest = GetHashClass();
             encContDigest = GetHashClass();
         }
         sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
         sig.Init(false, signCert.GetPublicKey());
     }
 }
示例#38
0
        protected void Sign(Stream signed, Stream unsigned, X509Certificate2 selectedCert)
        {
            BC::X509.X509Certificate bcSelectedCert = DotNetUtilities.FromX509Certificate(selectedCert);
            trace.TraceEvent(TraceEventType.Information, 0, "Signing the message in name of {0}", selectedCert.Subject);

            //Signing time
            DateTime signingTime = DateTime.UtcNow;

            CmsSignedDataStreamGenerator signedGenerator = new CmsSignedDataStreamGenerator();

            //For compatibility we don't add it to the CMS (most implementations, including BC, don't support OCSP here)
            //IX509Store crlStore = X509StoreFactory.Create("CRL/COLLECTION", new X509CollectionStoreParameters(crl's));
            //signedGenerator.AddCrls(crlStore);

            //add signed attributes to the signature (own signing time)
            IDictionary signedAttrDictionary = new Hashtable();
            BC::Asn1.Cms.Attribute signTimeattr = new BC::Asn1.Cms.Attribute(CmsAttributes.SigningTime,
                    new DerSet(new BC::Asn1.Cms.Time(signingTime)));
            signedAttrDictionary.Add(signTimeattr.AttrType, signTimeattr);
            BC::Asn1.Cms.AttributeTable signedAttrTable = new BC.Asn1.Cms.AttributeTable(signedAttrDictionary);

            //Add the signatures
            SignatureAlgorithm signAlgo;
            if (((RSACryptoServiceProvider)selectedCert.PrivateKey).CspKeyContainerInfo.Exportable) {
                signAlgo =  EteeActiveConfig.Seal.NativeSignatureAlgorithm;
                signedGenerator.AddSigner(DotNetUtilities.GetKeyPair(selectedCert.PrivateKey).Private,
                    bcSelectedCert, signAlgo.EncryptionAlgorithm.Value, signAlgo.DigestAlgorithm.Value,
                    signedAttrTable, null);
            } else {
                signAlgo = EteeActiveConfig.Seal.WindowsSignatureAlgorithm;
                signedGenerator.AddSigner(new ProxyRsaKeyParameters((RSACryptoServiceProvider)selectedCert.PrivateKey),
                    bcSelectedCert, signAlgo.EncryptionAlgorithm.Value, signAlgo.DigestAlgorithm.Value,
                    signedAttrTable, null);
            }
            trace.TraceEvent(TraceEventType.Verbose, 0, "Added Signer [EncAlgo={0} ({1}), DigestAlgo={2} ({3})",
                signAlgo.EncryptionAlgorithm.FriendlyName,
                signAlgo.EncryptionAlgorithm.Value,
                signAlgo.DigestAlgorithm.FriendlyName,
                signAlgo.DigestAlgorithm.Value);

            Stream signingStream = signedGenerator.Open(signed, true);
            trace.TraceEvent(TraceEventType.Verbose, 0, "Create embedded signed message (still empty)");
            try
            {
                unsigned.CopyTo(signingStream);
                trace.TraceEvent(TraceEventType.Verbose, 0, "Message copied and digest calculated");
            }
            finally
            {
                signingStream.Close();
                trace.TraceEvent(TraceEventType.Verbose, 0, "Signature block added");
            }
        }
示例#39
0
		/**
		 * Return a new table with the passed in attribute added.
		 *
		 * @param attrType
		 * @param attrValue
		 * @return
		 */
		public AttributeTable Add(DerObjectIdentifier attrType, Asn1Encodable attrValue)
		{
			AttributeTable newTable = new AttributeTable(attributes);

			newTable.AddAttribute(new Attribute(attrType, new DerSet(attrValue)));

			return newTable;
		}
示例#40
0
		public AttributeTable Remove(DerObjectIdentifier attrType)
		{
			AttributeTable newTable = new AttributeTable(attributes);

			newTable.attributes.Remove(attrType);

			return newTable;
		}