internal SignerInformation(Org.BouncyCastle.Asn1.Cms.SignerInfo info, DerObjectIdentifier contentType, CmsProcessable content, IDigestCalculator digestCalculator)
 {
     this.info               = info;
     this.sid                = new SignerID();
     this.contentType        = contentType;
     this.isCounterSignature = (contentType == null);
     try
     {
         SignerIdentifier signerID = info.SignerID;
         if (signerID.IsTagged)
         {
             Asn1OctetString instance = Asn1OctetString.GetInstance(signerID.ID);
             this.sid.SubjectKeyIdentifier = instance.GetEncoded();
         }
         else
         {
             Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber instance2 = Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber.GetInstance(signerID.ID);
             this.sid.Issuer       = instance2.Name;
             this.sid.SerialNumber = instance2.SerialNumber.Value;
         }
     }
     catch (IOException)
     {
         throw new ArgumentException("invalid sid in SignerInfo");
     }
     this.digestAlgorithm      = info.DigestAlgorithm;
     this.signedAttributeSet   = info.AuthenticatedAttributes;
     this.unsignedAttributeSet = info.UnauthenticatedAttributes;
     this.encryptionAlgorithm  = info.DigestEncryptionAlgorithm;
     this.signature            = info.EncryptedDigest.GetOctets();
     this.content          = content;
     this.digestCalculator = digestCalculator;
 }
Esempio n. 2
0
 private CmsSignedData(CmsSignedData c)
 {
     this.signedData      = c.signedData;
     this.contentInfo     = c.contentInfo;
     this.signedContent   = c.signedContent;
     this.signerInfoStore = c.signerInfoStore;
 }
Esempio n. 3
0
        /**
         * Generate an object that contains an CMS Compressed Data
         */
        public CmsCompressedData Generate(
            CmsProcessable content,
            string compressionOid)
        {
            AlgorithmIdentifier comAlgId;
            Asn1OctetString     comOcts;

            try
            {
                MemoryStream  bOut = new MemoryStream();
                ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION);

                content.Write(zOut);

                Platform.Dispose(zOut);

                comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid));
                comOcts  = new BerOctetString(bOut.ToArray());
            }
            catch (IOException e)
            {
                throw new CmsException("exception encoding data.", e);
            }

            ContentInfo comContent  = new ContentInfo(CmsObjectIdentifiers.Data, comOcts);
            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.CompressedData,
                new CompressedData(comAlgId, comContent));

            return(new CmsCompressedData(contentInfo));
        }
        public CmsCompressedData Generate(CmsProcessable content, string compressionOid)
        {
            //IL_0000: Unknown result type (might be due to invalid IL or missing references)
            //IL_0006: Expected O, but got Unknown
            //IL_0037: Expected O, but got Unknown
            AlgorithmIdentifier compressionAlgorithm;
            Asn1OctetString     content2;

            try
            {
                MemoryStream  val           = new MemoryStream();
                ZOutputStream zOutputStream = new ZOutputStream((Stream)(object)val, -1);
                content.Write((Stream)(object)zOutputStream);
                Platform.Dispose((Stream)(object)zOutputStream);
                compressionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid));
                content2             = new BerOctetString(val.ToArray());
            }
            catch (IOException val2)
            {
                IOException e = val2;
                throw new CmsException("exception encoding data.", (global::System.Exception)(object) e);
            }
            ContentInfo encapContentInfo = new ContentInfo(CmsObjectIdentifiers.Data, content2);
            ContentInfo contentInfo      = new ContentInfo(CmsObjectIdentifiers.CompressedData, new CompressedData(compressionAlgorithm, encapContentInfo));

            return(new CmsCompressedData(contentInfo));
        }
Esempio n. 5
0
        public static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
        {
            CmsProcessable signedContent = null;
            CmsSignedData  cmsSignedData = null;

            Org.BouncyCastle.X509.Store.IX509Store store = null;
            ICollection signers        = null;
            bool        verifiedStatus = false;

            try
            {
                //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
                signedContent = new CmsProcessableFile(contentFile);
                cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
                store         = cmsSignedData.GetCertificates("Collection");//.getCertificates();
                IX509Store certStore = cmsSignedData.GetCertificates("Collection");
                signers = cmsSignedData.GetSignerInfos().GetSigners();
                foreach (var item in signers)
                {
                    SignerInformation signer   = (SignerInformation)item;
                    var         certCollection = certStore.GetMatches(signer.SignerID);
                    IEnumerator iter           = certCollection.GetEnumerator();
                    iter.MoveNext();
                    var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
                    verifiedStatus = signer.Verify(cert.GetPublicKey());
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(verifiedStatus);
        }
Esempio n. 6
0
 private CmsSignedData(CmsSignedData c)
 {
     signedData      = c.signedData;
     contentInfo     = c.contentInfo;
     signedContent   = c.signedContent;
     signerInfoStore = c.signerInfoStore;
 }
        /**
        * Generate an object that contains an CMS Compressed Data
        */
        public CmsCompressedData Generate(
            CmsProcessable	content,
            string			compressionOid)
        {
            AlgorithmIdentifier comAlgId;
            Asn1OctetString comOcts;

            try
            {
                MemoryStream bOut = new MemoryStream();
                ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION);

                content.Write(zOut);

                zOut.Dispose();

                comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid));
                comOcts = new BerOctetString(bOut.ToArray());
            }
            catch (IOException e)
            {
                throw new CmsException("exception encoding data.", e);
            }

            ContentInfo comContent = new ContentInfo(CmsObjectIdentifiers.Data, comOcts);
            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.CompressedData,
                new CompressedData(comAlgId, comContent));

            return new CmsCompressedData(contentInfo);
        }
Esempio n. 8
0
        byte[] extractSignedContent(byte[] signedFile)
        {
            CmsSignedData  content       = new CmsSignedData(signedFile);
            CmsProcessable signedContent = content.SignedContent;

            return((byte[])signedContent.GetContent());
        }
Esempio n. 9
0
        /**
         * Generate an object that contains an CMS Compressed Data
         */
        public CmsCompressedData Generate(
            CmsProcessable content,
            string compressionOid)
        {
            AlgorithmIdentifier comAlgId;
            Asn1OctetString     comOcts;

            try
            {
                MemoryStream bOut = new MemoryStream();
                //DeflaterOutputStream zOut = null;

                //content.Write(zOut);

                //zOut.Close();

                comAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(compressionOid),
                    null);

                comOcts = new BerOctetString(bOut.ToArray());
            }
            catch (IOException e)
            {
                throw new CmsException("exception encoding data.", e);
            }

            ContentInfo comContent  = new ContentInfo(CmsObjectIdentifiers.Data, comOcts);
            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.CompressedData,
                new CompressedData(comAlgId, comContent));

            return(new CmsCompressedData(contentInfo));
        }
Esempio n. 10
0
		private CmsSignedData(
			CmsSignedData c)
		{
			this.signedData = c.signedData;
			this.contentInfo = c.contentInfo;
			this.signedContent = c.signedContent;
			this.signerInfoStore = c.signerInfoStore;
		}
Esempio n. 11
0
 public CmsSignedData(
     CmsProcessable signedContent,
     ContentInfo sigData)
 {
     this.signedContent = signedContent;
     this.contentInfo   = sigData;
     this.signedData    = SignedData.GetInstance(contentInfo.Content);
 }
    private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
    {
        KeyParameter        keyParameter;
        AlgorithmIdentifier algorithmIdentifier;
        Asn1OctetString     content2;
        Asn1OctetString     mac2;

        try
        {
            byte[] array = keyGen.GenerateKey();
            keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
            Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array);
            algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out ICipherParameters _);
            IMac mac = MacUtilities.GetMac(macOid);
            mac.Init(keyParameter);
            MemoryStream memoryStream = new MemoryStream();
            Stream       stream       = new TeeOutputStream(memoryStream, new MacOutputStream(mac));
            content.Write(stream);
            Platform.Dispose(stream);
            content2 = new BerOctetString(memoryStream.ToArray());
            byte[] str = MacUtilities.DoFinal(mac);
            mac2 = new DerOctetString(str);
        }
        catch (SecurityUtilityException e)
        {
            throw new CmsException("couldn't create cipher.", e);
        }
        catch (InvalidKeyException e2)
        {
            throw new CmsException("key invalid in message.", e2);
        }
        catch (IOException e3)
        {
            throw new CmsException("exception decoding algorithm parameters.", e3);
        }
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

        foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators)
        {
            try
            {
                asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
            }
            catch (InvalidKeyException e4)
            {
                throw new CmsException("key inappropriate for algorithm.", e4);
            }
            catch (GeneralSecurityException e5)
            {
                throw new CmsException("error making encrypted content.", e5);
            }
        }
        ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
        ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

        return(new CmsAuthenticatedData(contentInfo));
    }
Esempio n. 13
0
 public CmsSignedData(ContentInfo sigData)
 {
     contentInfo = sigData;
     signedData  = SignedData.GetInstance(contentInfo.Content);
     if (signedData.EncapContentInfo.Content != null)
     {
         signedContent = new CmsProcessableByteArray(((Asn1OctetString)signedData.EncapContentInfo.Content).GetOctets());
     }
 }
Esempio n. 14
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));
            }
        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));
        }
        public TimeStampToken(
            CmsSignedData signedData)
        {
            this.tsToken = signedData;

            if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id))
            {
                throw new TspValidationException("ContentInfo object not for a time stamp.");
            }

            ICollection signers = tsToken.GetSignerInfos().GetSigners();

            if (signers.Count != 1)
            {
                throw new ArgumentException("Time-stamp token signed by "
                                            + signers.Count
                                            + " signers, but it must contain just the TSA signature.");
            }


            IEnumerator signerEnum = signers.GetEnumerator();

            signerEnum.MoveNext();
            tsaSignerInfo = (SignerInformation)signerEnum.Current;

            try
            {
                CmsProcessable content = tsToken.SignedContent;
                MemoryStream   bOut    = new MemoryStream();

                content.Write(bOut);

                this.tstInfo = new TimeStampTokenInfo(
                    TstInfo.GetInstance(
                        Asn1Object.FromByteArray(bOut.ToArray())));

                Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
                    PkcsObjectIdentifiers.IdAASigningCertificate];

                if (attr == null)
                {
                    throw new TspValidationException(
                              "no signing certificate attribute found, time stamp invalid.");
                }

                SigningCertificate signCert = SigningCertificate.GetInstance(
                    attr.AttrValues[0]);

                this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);
            }
            catch (CmsException e)
            {
                throw new TspException(e.Message, e.InnerException);
            }
        }
Esempio n. 17
0
        public void PreGenerate(string signedContentType, CmsProcessable content)
        {
            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);
                }
            }
        }
Esempio n. 18
0
 public CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, int keySize)
 {
     try
     {
         CipherKeyGenerator keyGenerator = GeneratorUtilities.GetKeyGenerator(encryptionOid);
         keyGenerator.Init(new KeyGenerationParameters(rand, keySize));
         return(Generate(content, encryptionOid, keyGenerator));
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("can't find key generation algorithm.", e);
     }
 }
Esempio n. 19
0
        /// <summary>Add a signature to the already CMS signed data document.</summary>
        /// <remarks>Add a signature to the already CMS signed data document.</remarks>
        /// <param name="_signedDocument"></param>
        /// <param name="parameters"></param>
        /// <param name="signatureValue"></param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual Document AddASignatureToDocument(Document _signedDocument, SignatureParameters
                                                        parameters, byte[] signatureValue)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            try
            {
                CmsSignedData originalSignedData = null;
                using (var stream = _signedDocument.OpenStream())
                {
                    originalSignedData = new CmsSignedData(stream);
                }

                //jbonilla - No aplica para C#
                //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
                //    (parameters.GetDigestAlgorithm());
                //PreComputedContentSigner cs = new PreComputedContentSigner(jsAlgorithm, signatureValue
                //    );
                PreComputedSigner s = new PreComputedSigner(signatureValue);
                //DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider
                //    ();
                //CMSSignedDataGenerator generator = CreateCMSSignedDataGenerator(cs, digestCalculatorProvider
                //    , parameters, GetSigningProfile(parameters), true, originalSignedData);
                CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(s, parameters
                                                                                , GetSigningProfile(parameters), true, originalSignedData);

                //if (originalSignedData == null || originalSignedData.SignedContent.GetContent
                //    () == null)
                if (originalSignedData == null || originalSignedData.SignedContent == null)
                {
                    throw new RuntimeException("Cannot retrieve orignal content");
                }
                //byte[] octetString = (byte[])originalSignedData.SignedContent.GetContent();
                //CmsProcessableByteArray content = new CmsProcessableByteArray(octetString);
                CmsProcessable          content        = originalSignedData.SignedContent;
                CmsSignedData           data           = generator.Generate(content, true);
                Document                signedDocument = new CMSSignedDocument(data);
                CAdESSignatureExtension extension      = GetExtensionProfile(parameters);
                if (extension != null)
                {
                    signedDocument = extension.ExtendSignatures(new CMSSignedDocument(data), null, parameters);
                }
                return(signedDocument);
            }
            catch (CmsException e)
            {
                throw new RuntimeException(e);
            }
        }
            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));
            }
        /// <summary>Generate an enveloped object that contains an CMS Enveloped Data object.</summary>
        public CmsEnvelopedData Generate(
            CmsProcessable	content,
            string			encryptionOid)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                return Generate(content, encryptionOid, keyGen);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        // TODO Make public?
        internal void Generate(
            Stream outStream,
            string eContentType,
            bool encapsulate,
            Stream dataOutputStream,
            CmsProcessable content)
        {
            Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);

            if (content != null)
            {
                content.Write(signedOut);
            }
            BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(signedOut);
        }
        // TODO Make public?
        internal void Generate(
            Stream outStream,
            string eContentType,
            bool encapsulate,
            Stream dataOutputStream,
            CmsProcessable content)
        {
            Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);

            if (content != null)
            {
                content.Write(signedOut);
            }
            Platform.Dispose(signedOut);
        }
        public CmsAuthenticatedData Generate(CmsProcessable content, string encryptionOid)
        {
            CmsAuthenticatedData result;

            try
            {
                CipherKeyGenerator keyGenerator = GeneratorUtilities.GetKeyGenerator(encryptionOid);
                keyGenerator.Init(new KeyGenerationParameters(this.rand, keyGenerator.DefaultStrength));
                result = this.Generate(content, encryptionOid, keyGenerator);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
            return(result);
        }
Esempio n. 25
0
 /**
  * Protected constructor. In some cases clients have their own idea about how to encode
  * the signed attributes and calculate the signature. This constructor is to allow developers
  * to deal with that by extending off the class and overridng methods like getSignedAttributes().
  *
  * @param baseInfo the SignerInformation to base this one on.
  */
 protected SignerInformation(SignerInformation baseInfo)
 {
     this.info               = baseInfo.info;
     this.contentType        = baseInfo.contentType;
     this.isCounterSignature = baseInfo.IsCounterSignature;
     this.sid                    = baseInfo.SignerID;
     this.digestAlgorithm        = info.DigestAlgorithm;
     this.signedAttributeSet     = info.AuthenticatedAttributes;
     this.unsignedAttributeSet   = info.UnauthenticatedAttributes;
     this.encryptionAlgorithm    = info.DigestEncryptionAlgorithm;
     this.signature              = info.EncryptedDigest.GetOctets();
     this.content                = baseInfo.content;
     this.resultDigest           = baseInfo.resultDigest;
     this.signedAttributeTable   = baseInfo.signedAttributeTable;
     this.unsignedAttributeTable = baseInfo.unsignedAttributeTable;
 }
Esempio n. 26
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)
            {
                var content = signedData.EncapContentInfo.Content;
                this.signedContent = new CmsProcessableByteArray(
                    content.GetEncoded());
            }
        }
    public TimeStampToken(CmsSignedData signedData)
    {
        tsToken = signedData;
        if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
        {
            throw new TspValidationException("ContentInfo object not for a time stamp.");
        }
        ICollection signers = tsToken.GetSignerInfos().GetSigners();

        if (signers.Count != 1)
        {
            throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature.");
        }
        IEnumerator enumerator = signers.GetEnumerator();

        enumerator.MoveNext();
        tsaSignerInfo = (SignerInformation)enumerator.Current;
        try
        {
            CmsProcessable signedContent = tsToken.SignedContent;
            MemoryStream   memoryStream  = new MemoryStream();
            signedContent.Write(memoryStream);
            tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(memoryStream.ToArray())));
            Org.BouncyCastle.Asn1.Cms.Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
            if (attribute != null)
            {
                SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0]));
            }
            else
            {
                attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
                if (attribute == null)
                {
                    throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
                }
                SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]);
                certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0]));
            }
        }
        catch (CmsException ex)
        {
            throw new TspException(ex.Message, ex.InnerException);
        }
    }
Esempio n. 28
0
        /**
         * generate an authenticated object that contains an CMS Authenticated Data object
         */
        public CmsAuthenticatedData Generate(
            CmsProcessable content,
            string encryptionOid)
        {
            try
            {
                // FIXME Will this work for macs?
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                return(Generate(content, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        /**
         * generate an authenticated object that contains an CMS Authenticated Data object
         */
        public CmsAuthenticatedData Generate(
	        CmsProcessable	content,
	        string			encryptionOid)
        {
            try
            {
                // FIXME Will this work for macs?
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                return Generate(content, encryptionOid, keyGen);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        /// <summary>Generate an enveloped object that contains an CMS Enveloped Data object.</summary>
        public CmsEnvelopedData Generate(
            CmsProcessable  content,
            string          encryptionOid,
            int             keySize)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                keyGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize));

                return Generate(content, encryptionOid, keyGen);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
		internal SignerInformation(
			SignerInfo			info,
			DerObjectIdentifier	contentType,
			CmsProcessable		content,
			IDigestCalculator	digestCalculator)
		{
			this.info = info;
			this.sid = new SignerID();
			this.contentType = contentType;
			this.isCounterSignature = contentType == null;

			try
			{
				SignerIdentifier s = info.SignerID;

				if (s.IsTagged)
				{
					Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID);

					sid.SubjectKeyIdentifier = octs.GetEncoded();
				}
				else
				{
					Asn1.Cms.IssuerAndSerialNumber iAnds =
						Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID);

					sid.Issuer = iAnds.Name;
					sid.SerialNumber = iAnds.SerialNumber.Value;
				}
			}
			catch (IOException)
			{
				throw new ArgumentException("invalid sid in SignerInfo");
			}

			this.digestAlgorithm = info.DigestAlgorithm;
			this.signedAttributeSet = info.AuthenticatedAttributes;
			this.unsignedAttributeSet = info.UnauthenticatedAttributes;
			this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
			this.signature = info.EncryptedDigest.GetOctets();

			this.content = content;
			this.digestCalculator = digestCalculator;
		}
Esempio n. 32
0
 public TimeStampToken(CmsSignedData signedData)
 {
     //IL_0063: Unknown result type (might be due to invalid IL or missing references)
     //IL_0094: Unknown result type (might be due to invalid IL or missing references)
     //IL_009a: Expected O, but got Unknown
     tsToken = signedData;
     if (!tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
     {
         throw new TspValidationException("ContentInfo object not for a time stamp.");
     }
     global::System.Collections.ICollection signers = tsToken.GetSignerInfos().GetSigners();
     if (signers.get_Count() != 1)
     {
         throw new ArgumentException(string.Concat((object)"Time-stamp token signed by ", (object)signers.get_Count(), (object)" signers, but it must contain just the TSA signature."));
     }
     global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)signers).GetEnumerator();
     enumerator.MoveNext();
     tsaSignerInfo = (SignerInformation)enumerator.get_Current();
     try
     {
         CmsProcessable signedContent = tsToken.SignedContent;
         MemoryStream   val           = new MemoryStream();
         signedContent.Write((Stream)(object)val);
         tstInfo = new TimeStampTokenInfo(TstInfo.GetInstance(Asn1Object.FromByteArray(val.ToArray())));
         Attribute attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
         if (attribute != null)
         {
             SigningCertificate instance = SigningCertificate.GetInstance(attribute.AttrValues[0]);
             certID = new CertID(EssCertID.GetInstance(instance.GetCerts()[0]));
             return;
         }
         attribute = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
         if (attribute == null)
         {
             throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
         }
         SigningCertificateV2 instance2 = SigningCertificateV2.GetInstance(attribute.AttrValues[0]);
         certID = new CertID(EssCertIDv2.GetInstance(instance2.GetCerts()[0]));
     }
     catch (CmsException ex)
     {
         throw new TspException(((global::System.Exception)ex).get_Message(), ((global::System.Exception)ex).get_InnerException());
     }
 }
        // TODO Make public?
        internal void Generate(
            Stream outStream,
            string eContentType,
            bool encapsulate,
            Stream dataOutputStream,
            CmsProcessable content)
        {
            Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);

            if (content != null)
            {
                content.Write(signedOut);
            }
#if !NETFX_CORE
            signedOut.Close();
#else
            signedOut.Dispose();
#endif
        }
Esempio n. 34
0
        private bool ExcractLcoSignedData()
        {
            Logger.Info("Decodificando el archivo");

            var            s  = new CmsSignedData(File.ReadAllBytes(LCOFilePath + "lco_firmado.xml"));
            CmsProcessable cp = s.SignedContent;

            byte[] original = (byte[])cp.GetContent();

            Logger.Info("Cargando el XMLDocument");
            File.WriteAllBytes(LCOFilePath + "lco.xml", original);//, Encoding.ASCII.GetString(sigLFirma.ContentInfo.Content));

            var xmlPDoc = new XmlDocument();


            xmlPDoc.Load(LCOFilePath + "lco.xml");//LoadXml(Encoding.ASCII.GetString(original));//sigLFirma.ContentInfo.Content));

            return(this.ParseXmlLco(xmlPDoc));
        }
Esempio n. 35
0
        internal SignerInformation(
            SignerInfo info,
            DerObjectIdentifier contentType,
            CmsProcessable content,
            byte[]                          digest)
        {
            this.info        = info;
            this.sid         = new SignerID();
            this.contentType = contentType;

            try
            {
                SignerIdentifier s = info.SignerID;

                if (s.IsTagged)
                {
                    Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID);

                    sid.SubjectKeyIdentifier = octs.GetOctets();
                }
                else
                {
                    Asn1.Cms.IssuerAndSerialNumber iAnds =
                        Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID);

                    sid.Issuer       = iAnds.Name;
                    sid.SerialNumber = iAnds.SerialNumber.Value;
                }
            }
            catch (IOException)
            {
                throw new ArgumentException("invalid sid in SignerInfo");
            }

            this.digestAlgorithm     = info.DigestAlgorithm;
            this.signedAttributes    = info.AuthenticatedAttributes;
            this.unsignedAttributes  = info.UnauthenticatedAttributes;
            this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
            this.signature           = info.EncryptedDigest.GetOctets();

            this.content = content;
            _digest      = digest;
        }
Esempio n. 36
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;
//			}
        }
 // TODO Make public?
 internal void Generate(
     Stream			outStream,
     string			eContentType,
     bool			encapsulate,
     Stream			dataOutputStream,
     CmsProcessable	content)
 {
     Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);
     if (content != null)
     {
         content.Write(signedOut);
     }
     signedOut.Close();
 }
        /// <summary>
        /// Generate an enveloped object that contains a CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private CmsEnvelopedData Generate(
            CmsProcessable		content,
            string				encryptionOid,
            CipherKeyGenerator	keyGen)
        {
            AlgorithmIdentifier encAlgId = null;
            KeyParameter encKey;
            Asn1OctetString encContent;

            try
            {
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);

                ICipherParameters cipherParameters;
                encAlgId = GetAlgorithmIdentifier(
                    encryptionOid, encKey, asn1Params, out cipherParameters);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
                cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));

                MemoryStream bOut = new MemoryStream();
                CipherStream cOut = new CipherStream(bOut, null, cipher);

                content.Write(cOut);

                cOut.Dispose();

                encContent = new BerOctetString(bOut.ToArray());
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                CmsObjectIdentifiers.Data,
                encAlgId,
                encContent);

            Asn1Set unprotectedAttrSet = null;
            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.EnvelopedData,
                new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet));

            return new CmsEnvelopedData(contentInfo);
        }
	    /**
	     * generate an enveloped object that contains an CMS Enveloped Data
	     * object using the given provider and the passed in key generator.
	     */
		private CmsAuthenticatedData Generate(
			CmsProcessable		content,
			string				macOid,
			CipherKeyGenerator	keyGen)
		{
			AlgorithmIdentifier macAlgId;
			KeyParameter encKey;
			Asn1OctetString encContent;
			Asn1OctetString macResult;

			try
			{
				// FIXME Will this work for macs?
				byte[] encKeyBytes = keyGen.GenerateKey();
				encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

				Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

				ICipherParameters cipherParameters;
				macAlgId = GetAlgorithmIdentifier(
				macOid, encKey, asn1Params, out cipherParameters);

				IMac mac = MacUtilities.GetMac(macOid);
				// TODO Confirm no ParametersWithRandom needed
				// FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
				mac.Init(encKey);

				MemoryStream bOut = new MemoryStream();
				Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

				content.Write(mOut);

				mOut.Close();
				bOut.Close();

				encContent = new BerOctetString(bOut.ToArray());

				byte[] macOctets = MacUtilities.DoFinal(mac);
				macResult = new DerOctetString(macOctets);
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
			catch (IOException e)
			{
				throw new CmsException("exception decoding algorithm parameters.", e);
			}

			Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

			foreach (RecipientInfoGenerator rig in recipientInfoGenerators) 
			{
				try
				{
					recipientInfos.Add(rig.Generate(encKey, rand));
				}
				catch (InvalidKeyException e)
				{
					throw new CmsException("key inappropriate for algorithm.", e);
				}
				catch (GeneralSecurityException e)
				{
					throw new CmsException("error making encrypted content.", e);
				}
			}
			
			ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);
			
			ContentInfo contentInfo = new ContentInfo(
			CmsObjectIdentifiers.AuthenticatedData,
			new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));
			
			return new CmsAuthenticatedData(contentInfo);
		}
Esempio n. 40
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,
            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));
				signerInfos.Add(signer.ToSignerInfo());
            }

			//
            // add the SignerInfo objects
            //
			DerObjectIdentifier contentTypeOID;
			bool isCounterSignature;

			if (signedContentType != null)
			{
				contentTypeOID = new DerObjectIdentifier(signedContentType);
				isCounterSignature = false;
			}
			else
			{
				contentTypeOID = CmsObjectIdentifiers.Data;
				isCounterSignature = true;
			}

			foreach (SignerInf signer in signerInfs)
            {
				try
                {
					digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
					signerInfos.Add(signer.ToSignerInfo(contentTypeOID, content, rand, isCounterSignature));
				}
                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();
                try
                {
                    content.Write(bOut);
                }
                catch (IOException e)
                {
                    throw new CmsException("encapsulation error.", e);
                }

				octs = new BerOctetString(bOut.ToArray());
            }

			Asn1.Cms.ContentInfo encInfo = new Asn1.Cms.ContentInfo(contentTypeOID, octs);

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

            Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo(
                PkcsObjectIdentifiers.SignedData, sd);

            return new CmsSignedData(content, contentInfo);
        }
 /**
 * 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 with the
 * default content type "data".
 */
 public CmsSignedData Generate(
     CmsProcessable	content,
     bool			encapsulate)
 {
     return this.Generate(Data, content, encapsulate);
 }
Esempio n. 42
0
			internal Asn1.Cms.SignerInfo ToSignerInfo(
                DerObjectIdentifier	contentType,
                CmsProcessable		content,
				SecureRandom		random,
				bool				isCounterSignature)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);
				string digestName = Helper.GetDigestAlgName(digestOID);
				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
				ISigner sig = Helper.GetSignatureInstance(signatureName);
				IDigest dig = Helper.GetDigestInstance(digestName);

                byte[] hash = null;

                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));

					hash = DigestUtilities.DoFinal(dig);

					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;

				if (isCounterSignature)
				{
					Hashtable ats = signed.ToHashtable();

					ats.Remove(CmsAttributes.ContentType);

					signed = new Asn1.Cms.AttributeTable(ats);
				}

				Asn1Set signedAttr = outer.GetAttributeSet(signed);


				//
                // sig must be composed from the DER encoding.
                //
				byte[] tmp;
				if (signedAttr != null)
                {
					tmp = signedAttr.GetEncoded(Asn1Encodable.Der);
                }
                else
                {
					MemoryStream bOut = new MemoryStream();
					content.Write(bOut);
					tmp = bOut.ToArray();
                }

				sig.Init(true, new ParametersWithRandom(key, random));
				sig.BlockUpdate(tmp, 0, tmp.Length);

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

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

				Asn1.Cms.AttributeTable unsigned = (unsAttr != null)
//					?	unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters))
					?	unsAttr.GetAttributes(baseParameters)
					:	null;

				Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate cert = this.GetCertificate();
	            SignerIdentifier identifier;
	            if (cert != null)
	            {
					TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
						Asn1Object.FromByteArray(cert.GetTbsCertificate()));
					Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
						tbs.Issuer, tbs.SerialNumber.Value);
	            	identifier = new SignerIdentifier(encSid);
	            }
	            else
	            {
	                identifier = new SignerIdentifier(new DerOctetString(keyIdentifier));
	            }

                return new Asn1.Cms.SignerInfo(identifier, digAlgId,
                    signedAttr, encAlgId, encDigest, unsignedAttr);
            }
        /// <summary>
        /// Generate an enveloped object that contains a CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private CmsEnvelopedData Generate(
            CmsProcessable		content,
            string				encryptionOid,
            CipherKeyGenerator	keyGen)
        {
            AlgorithmIdentifier encAlgId = null;
            KeyParameter encKey;
            Asn1OctetString encContent;

            try
            {
                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);

                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);

                Asn1Encodable asn1Params = null;

                try
                {
                    if (encryptionOid.Equals(RC2Cbc))
                    {
                        // mix in a bit extra...
                        rand.SetSeed(DateTime.Now.Ticks);

                        byte[] iv = rand.GenerateSeed(8);

                        // TODO Is this detailed repeat of Java version really necessary?
                        int effKeyBits = encKeyBytes.Length * 8;
                        int parameterVersion;

                        if (effKeyBits < 256)
                        {
                            parameterVersion = rc2Table[effKeyBits];
                        }
                        else
                        {
                            parameterVersion = effKeyBits;
                        }

                        asn1Params = new RC2CbcParameter(parameterVersion, iv);
                    }
                    else
                    {
                        asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand);
                    }
                }
                catch (SecurityUtilityException)
                {
                    // No problem... no parameters generated
                }

                Asn1Object asn1Object;
                ICipherParameters cipherParameters;

                if (asn1Params != null)
                {
                    asn1Object = asn1Params.ToAsn1Object();
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        encryptionOid, encKey, asn1Object);
                }
                else
                {
                    asn1Object = DerNull.Instance;
                    cipherParameters = encKey;
                }

                encAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(encryptionOid),
                    asn1Object);

                cipher.Init(true, cipherParameters);

                MemoryStream bOut = new MemoryStream();
                CipherStream cOut = new CipherStream(bOut, null, cipher);

                content.Write(cOut);

                cOut.Close();

                encContent = new BerOctetString(bOut.ToArray());
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInf recipient in recipientInfs)
            {
                try
                {
                    recipientInfos.Add(recipient.ToRecipientInfo(encKey));
                }
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                PkcsObjectIdentifiers.Data,
                encAlgId,
                encContent);

            Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo(
                PkcsObjectIdentifiers.EnvelopedData,
                new EnvelopedData(null, new DerSet(recipientInfos), eci, null));

            return new CmsEnvelopedData(contentInfo);
        }
		/**
        * generate a signed object that for a CMS Signed Data object
        */
        public CmsSignedData Generate(
            CmsProcessable content)
        {
            return Generate(content, false);
        }
Esempio n. 45
0
		public CmsSignedData(
			CmsProcessable  signedContent,
			ContentInfo     sigData)
		{
			this.signedContent = signedContent;
			this.contentInfo = sigData;
			this.signedData = SignedData.GetInstance(contentInfo.Content);
		}
Esempio n. 46
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;
//			}
		}
        /**
        * 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);
        }
Esempio n. 48
0
		public CmsSignedData(
			CmsProcessable	signedContent,
			byte[]			sigBlock)
			: this(signedContent, CmsUtilities.ReadContentInfo(new MemoryStream(sigBlock, false)))
		{
		}
			internal SignerInfo ToSignerInfo(
                DerObjectIdentifier	contentType,
                CmsProcessable		content,
				SecureRandom		random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
				string digestName = Helper.GetDigestAlgName(digestOID);

				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
				ISigner sig = Helper.GetSignatureInstance(signatureName);

                byte[] hash;
                if (outer._digests.Contains(digestOID))
                {
                    hash = (byte[])outer._digests[digestOID];
                }
                else
                {
                    IDigest dig = Helper.GetDigestInstance(digestName);
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(dig));
                    }
                    hash = DigestUtilities.DoFinal(dig);
                    outer._digests.Add(digestOID, hash.Clone());
                }

				sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
				Stream sigStr = new SigOutputStream(sig);
#else
				Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif

				Asn1Set signedAttr = null;
				if (sAttr != null)
				{
					IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new Asn1.Cms.AttributeTable(tmpSigned);
                        }
                    }

					// TODO Validate proposed signed attributes

					signedAttr = outer.GetAttributeSet(signed);

					// sig must be composed from the DER encoding.
					new DerOutputStream(sigStr).WriteObject(signedAttr);
				}
                else if (content != null)
                {
					// TODO Use raw signature of the hash value instead
					content.Write(sigStr);
                }

				sigStr.Close();
				byte[] sigBytes = sig.GenerateSignature();

				Asn1Set unsignedAttr = null;
				if (unsAttr != null)
				{
					IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
					baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

					// TODO Validate proposed unsigned attributes

					unsignedAttr = outer.GetAttributeSet(unsigned);
				}

				// TODO[RSAPSS] Need the ability to specify non-default parameters
				Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(
					new DerObjectIdentifier(encOID), sigX509Parameters);
				
                return new SignerInfo(signerIdentifier, digAlgId,
                    signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr);
            }
Esempio n. 50
0
		/**
		* base constructor - content with detached signature.
		*
		* @param signedContent the content that was signed.
		* @param sigData the signature object.
		*/
		public CmsSignedData(
			CmsProcessable	signedContent,
			Stream			sigData)
			: this(signedContent, CmsUtilities.ReadContentInfo(sigData))
		{
		}