Exemplo n.º 1
0
        /// <param name="signedData"></param>
        /// <returns></returns>
        public virtual CmsSignedData ExtendCMSSignedData(CmsSignedData signedData, Document
                                                         originalData, SignatureParameters parameters)
        {
            SignerInformationStore   signerStore = signedData.GetSignerInfos();
            List <SignerInformation> siArray     = new List <SignerInformation>();
            //Iterator<SignerInformation> infos = signerStore.GetSigners().Iterator();
            IEnumerator infos = signerStore.GetSigners().GetEnumerator();

            while (infos.MoveNext())
            {
                SignerInformation si = (SignerInformation)infos.Current;
                try
                {
                    siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                }
                catch (IOException)
                {
                    //LOG.Error("Exception when extending signature");
                    siArray.Add(si);
                }
            }
            SignerInformationStore newSignerStore = new SignerInformationStore(siArray);

            return(CmsSignedData.ReplaceSigners(signedData, newSignerStore));
        }
Exemplo n.º 2
0
        //  Sign the message with the private key of the signer.
        static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, bool UsaTSA, string TSAurl, string TSAuser, string TSApass)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(signerCert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)signerCert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(signerCert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                CmsProcessableByteArray file    = new CmsProcessableByteArray(msg); //CmsProcessableFile(File);
                CmsSignedData           Firmato = cms.Generate(file, false);        //se settato a true, il secondo argomento integra l'intero file

                byte[] bb = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(bb);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    bb = sd.GetEncoded();
                }
                return(bb);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
Exemplo n.º 3
0
        internal void ReBuildCmsSignedData()
        {
            IList <SignerInformation> list = new List <SignerInformation>();

            foreach (var node in _nodes)
            {
                list.Add(GetSignerInformation(node));
            }

            _signedData = CmsSignedData.ReplaceSigners(_signedData, new SignerInformationStore(list.ToArray()));
            ReadSignersInfo();
        }
Exemplo n.º 4
0
        private byte[] TimestampAuthorityResponse(EstEIDReader estEidReader, byte[] signedPkcs)
        {
            ArrayList newSigners = new ArrayList();

            CmsSignedData sd = new CmsSignedData(signedPkcs);

            foreach (SignerInformation si in sd.GetSignerInfos().GetSigners())
            {
                // possible TSA URLs
                //string TsaServerUrl = "http://www.edelweb.fr/cgi-bin/service-tsp";
                //string TsaServerUrl = "http://dse200.ncipher.com/TSS/HttpTspServer";

                byte[] signedDigest  = si.GetSignature();
                byte[] timeStampHash = ComputeHash(estEidReader, signedDigest);

                string TsaServerUrl = stamp.Url;
                string TsaUser      = stamp.User;
                string TsaPassword  = stamp.Password;
                string error        = string.Empty;

                byte[] timeStampToken = X509Utils.GetTimestampToken(TsaServerUrl,
                                                                    TsaUser,
                                                                    TsaPassword,
                                                                    timeStampHash,
                                                                    ref error);

                if (timeStampToken == null)
                {
                    throw new Exception(Resources.TSA_ERROR + error);
                }

                Hashtable  ht     = new Hashtable();
                Asn1Object derObj = new Asn1InputStream(timeStampToken).ReadObject();
                DerSet     derSet = new DerSet(derObj);

                Org.BouncyCastle.Asn1.Cms.Attribute unsignAtt = new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(X509Utils.ID_TIME_STAMP_TOKEN), derSet);

                ht.Add(X509Utils.ID_TIME_STAMP_TOKEN, unsignAtt);

                Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAtts = new Org.BouncyCastle.Asn1.Cms.AttributeTable(ht);

                newSigners.Add(SignerInformation.ReplaceUnsignedAttributes(si, unsignedAtts));
            }

            SignerInformationStore newSignerInformationStore = new SignerInformationStore(newSigners);

            CmsSignedData newSd = CmsSignedData.ReplaceSigners(sd, newSignerInformationStore);

            // Encode the CMS/PKCS #7 message
            return(newSd.GetEncoded());
        }
Exemplo n.º 5
0
        private static PrimarySignature RemoveUnsignedAttribute(PrimarySignature signature, Func <AttributeTable, AttributeTable> remover)
        {
            var bytes       = signature.GetBytes();
            var signedData  = new CmsSignedData(bytes);
            var signerInfos = signedData.GetSignerInfos();
            var signerInfo  = GetFirstSignerInfo(signerInfos);

            var updatedAttributes  = remover(signerInfo.UnsignedAttributes);
            var updatedSignerInfo  = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes);
            var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo);

            var updatedSignedData = CmsSignedData.ReplaceSigners(signedData, updatedSignerInfos);

            return(PrimarySignature.Load(updatedSignedData.GetEncoded()));
        }
Exemplo n.º 6
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignatures(Document document, Document originalData
                                                 , SignatureParameters parameters)
        {
            try
            {
                CmsSignedData            signedData  = new CmsSignedData(document.OpenStream());
                SignerInformationStore   signerStore = signedData.GetSignerInfos();
                List <SignerInformation> siArray     = new List <SignerInformation>();

                foreach (SignerInformation si in signerStore.GetSigners())
                {
                    try
                    {
                        //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida.
                        //Se asume que sólo se extiende las firmas desde BES.
                        //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL).
                        if (si.UnsignedAttributes.Count == 0)
                        {
                            siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                        }
                        else
                        {
                            //LOG.Error("Already extended?");
                            siArray.Add(si);
                        }
                    }
                    catch (IOException)
                    {
                        //LOG.Error("Exception when extending signature");
                        siArray.Add(si);
                    }
                }

                SignerInformationStore newSignerStore = new SignerInformationStore(siArray);
                CmsSignedData          extended       = CmsSignedData.ReplaceSigners(signedData, newSignerStore);
                return(new InMemoryDocument(extended.GetEncoded()));
            }
            catch (CmsException)
            {
                throw new IOException("Cannot parse CMS data");
            }
        }
        private static SignedCms ModifyUnsignedAttributes(SignedCms signedCms, Func <AttributeTable, AttributeTable> modify)
        {
            byte[] bytes = signedCms.Encode();

            var bcSignedCms = new CmsSignedData(bytes);
            SignerInformationStore signerInfos = bcSignedCms.GetSignerInfos();
            SignerInformation      signerInfo  = GetFirstSignerInfo(signerInfos);

            AttributeTable updatedAttributes = modify(signerInfo.UnsignedAttributes);

            SignerInformation updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes);
            var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo);

            CmsSignedData updatedBcSignedCms = CmsSignedData.ReplaceSigners(bcSignedCms, updatedSignerInfos);

            var updatedSignedCms = new SignedCms();

            updatedSignedCms.Decode(updatedBcSignedCms.GetEncoded());

            return(updatedSignedCms);
        }
Exemplo n.º 8
0
        private static PrimarySignature RemoveRepositoryCountersignatureTimestamp(PrimarySignature signature)
        {
            var bytes       = signature.GetBytes();
            var signedData  = new CmsSignedData(bytes);
            var signerInfos = signedData.GetSignerInfos();
            var signerInfo  = GetFirstSignerInfo(signerInfos);

            var countersignerInfos             = signerInfo.GetCounterSignatures();
            var countersignerInfo              = GetFirstSignerInfo(countersignerInfos);
            var updatedCountersignerAttributes = countersignerInfo.UnsignedAttributes.Remove(new DerObjectIdentifier(Oids.SignatureTimeStampTokenAttribute));
            var updatedCountersignerInfo       = SignerInformation.ReplaceUnsignedAttributes(countersignerInfo, updatedCountersignerAttributes);
            var updatedSignerAttributes        = signerInfo.UnsignedAttributes.Remove(new DerObjectIdentifier(Oids.Countersignature));

            updatedSignerAttributes = updatedSignerAttributes.Add(CmsAttributes.CounterSignature, updatedCountersignerInfo.ToSignerInfo());

            var updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedSignerAttributes);

            var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo);
            var updatedSignedData  = CmsSignedData.ReplaceSigners(signedData, updatedSignerInfos);

            return(PrimarySignature.Load(updatedSignedData.GetEncoded()));
        }
Exemplo n.º 9
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignature(object signatureId, Document document, Document
                                                originalData, SignatureParameters parameters)
        {
            SignerID toExtendId = (SignerID)signatureId;

            try
            {
                CmsSignedData            signedData  = new CmsSignedData(document.OpenStream());
                SignerInformationStore   signerStore = signedData.GetSignerInfos();
                List <SignerInformation> siArray     = new List <SignerInformation>();
                //Iterator<object> infos = signerStore.GetSigners().Iterator();
                IEnumerator infos = signerStore.GetSigners().GetEnumerator();
                while (infos.MoveNext())
                {
                    SignerInformation si = (SignerInformation)infos.Current;
                    if (si.SignerID.Equals(toExtendId))
                    {
                        try
                        {
                            siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                        }
                        catch (IOException)
                        {
                            //LOG.Error("Exception when extending signature");
                            siArray.Add(si);
                        }
                    }
                }
                SignerInformationStore newSignerStore = new SignerInformationStore(siArray);
                CmsSignedData          extended       = CmsSignedData.ReplaceSigners(signedData, newSignerStore);
                return(new InMemoryDocument(extended.GetEncoded()));
            }
            catch (CmsException)
            {
                throw new IOException("Cannot parse CMS data");
            }
        }
Exemplo n.º 10
0
        public byte[] FirmaFileBouncy(string NomeFile, X509Certificate2 cert, bool GiaFirmato, bool UsaTSA, string TSAurl, string TSAuser, string TSApass, out string RisFirma)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(cert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //mi ricavo il file da firmare
                FileInfo FileDaAprire = new FileInfo(NomeFile);

                /*CmsSignedData Firmato;
                 * if (GiaFirmato) {
                 *      CmsSignedData signedData = new CmsSignedData(File.ReadAllBytes(NomeFile));
                 *      if (signedData!=null){
                 *              SignerInformationStore signers = signedData.GetSignerInfos();
                 *              certList.Add(signers.GetSigners());
                 *              //MessageBox.Show(signedData.ContentInfo.GetEncoded().Length.ToString());
                 *              //signedData.ContentInfo.GetEncoded();
                 *      }
                 *      certList.Insert(0,certCopy);
                 *      CmsProcessableByteArray file = new CmsProcessableByteArray(signedData.ContentInfo.GetEncoded());
                 *      Firmato = cms.Generate(file, true);
                 * } else {
                 *      certList.Add(certCopy);
                 *      CmsProcessableFile file = new CmsProcessableFile(FileDaAprire);
                 *      Firmato = cms.Generate(file, true);
                 * }
                 */
                CmsProcessableFile file    = new CmsProcessableFile(FileDaAprire);
                CmsSignedData      Firmato = cms.Generate(file, true);
                byte[]             Encoded = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(Encoded);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd      = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    Encoded = sd.GetEncoded();
                }
                RisFirma = "";
                return(Encoded);
            }
            catch (Exception ex)
            {
                RisFirma = ex.ToString();
                return(null);
            }
        }