コード例 #1
0
        static void SignManifest(ZipFile zipFile, byte[] manifestFileData, X509Certificate2 signingCertificate, X509Certificate2Collection chainCertificates)
        {
            var signingCert = DotNetUtilities.FromX509Certificate(signingCertificate);

            var certList = new System.Collections.ArrayList();

            foreach (X509Certificate2 cert in chainCertificates)
            {
                certList.Add(DotNetUtilities.FromX509Certificate(cert));
            }

            var privateKey = DotNetUtilities.GetKeyPair(signingCertificate.PrivateKey).Private;
            var generator  = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, signingCert, CmsSignedDataGenerator.DigestSha1);

            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);

            generator.AddCertificates(st1);

            var content    = new CmsProcessableByteArray(manifestFileData);
            var signedData = generator.Generate(content, false);

            var data = signedData.GetEncoded();

            zipFile.AddEntry("signature", data);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: ditecsk/PadesInfoProcessor
        //private static string processSignedData(byte[] cadesData)
        //{


        //    string output = string.Empty;
        //    Utils.Cades.CAdESParser cades = new Utils.Cades.CAdESParser(cadesData);
        //    if (!cades.IsInitialized())
        //    {
        //        Console.Error.Write("PadesInfoProcessor.processSignedData: Nepodarilo sa inicializovat CAdESParser. Detail: " + cades.ErrorMessage);
        //        return null;
        //    }



        //    long signerInfoCount = cades.GetSignerInfoCount();

        //    for (int n = 0; n < signerInfoCount; n++)
        //    {
        //        output += "<SignerInfo>";
        //        try
        //        {
        //            //XmlDocument xSignatureDoc = DocUtility.CreateXmlDocument(xSignatureNode.OuterXml);

        //            //get xades type
        //            Utils.Cades.CAdESParser.CadesZepType zt = cades.GetSignatureType(n);
        //            Utils.Cades.CAdESParser.CadesBaselineProfileConfLevel confLevel = cades.GetSignatureConformanceLevel(n);
        //            if (zt == Utils.Cades.CAdESParser.CadesZepType.Unknown)
        //            {
        //                throw new Exception("Unknown CAdES type found.");
        //            }

        //            //get signing certificate subjects CN
        //            byte[] sigCertData = cades.GetSigningCertificate(n);

        //            //X509Certificate signingCert = new X509CertificateParser().ReadCertificate(sigCertData);
        //            //string signingCertInfo = this.getSigningCertInfo(signingCert);


        //            //create cades node
        //            int version;
        //            string hashAlgorithmOid;
        //            string signatureAlgOid;
        //            DateTime? signingTime;
        //            string messageDigestB64;
        //            string signaturePolicyOid;
        //            string sigPolicyHashAlgorithm;
        //            string sigPolicyHashValue;
        //            string contentType;
        //            string signatureValueB64;
        //            cades.GetSignerInfoParameters(n, out version, out hashAlgorithmOid, out signatureAlgOid, out signingTime, out messageDigestB64, out signaturePolicyOid, out sigPolicyHashAlgorithm, out sigPolicyHashValue, out contentType, out signatureValueB64);

        //            output += "<SignatureType>" + (signaturePolicyOid == null ? "PAdES_BES" : "PAdES_EPES") + "</SignatureType>";
        //            output += "<SigningCertificate>" + Convert.ToBase64String(sigCertData) + "</SigningCertificate>";
        //            output += "<SigningTime>" + (signingTime.HasValue ? signingTime.Value.ToUniversalTime().ToString("o") : "") + "</SigningTime>";

        //            output += "<TimeStamps>";
        //            List<object> timeStamps = new List<object>();
        //            if (zt >= Utils.Cades.CAdESParser.CadesZepType.CAdES_T)
        //            {

        //                //add timestamp info for T
        //                int sigTimeStampCount = cades.GetSignatureTimeStampCount(n);
        //                for (long ts = 0; ts < sigTimeStampCount; ts++)
        //                {
        //                    TimeStampToken timeStampToken = new TimeStampToken(new Org.BouncyCastle.Cms.CmsSignedData(cades.GetSignatureTimeStampToken(ts, n)));
        //                    output += "<TimeStamp>";
        //                    output += "<TimeStampDateTimeUtc>";
        //                    output += DateTime.SpecifyKind(timeStampToken.TimeStampInfo.GenTime, DateTimeKind.Utc).ToUniversalTime().ToString();
        //                    output += "</TimeStampDateTimeUtc>";
        //                    output += "<TimeStampSignatureCertificate>";
        //                    output += Convert.ToBase64String(getTimeStampCert(timeStampToken).GetEncoded());
        //                    output += "</TimeStampSignatureCertificate>";
        //                    output += "</TimeStamp>";
        //                }
        //            }
        //            output += "</TimeStamps>";

        //            //this.authorizations.Add(new Authorization(authObjs, null, signingTime.HasValue ? signingTime.Value : DateTime.MinValue, "CAdES", zt.ToString(), signingCert), zt >= CAdESParser.CadesZepType.CAdES_T, timeStamps));
        //        }
        //        catch (Exception ex)
        //        {
        //            Console.Error.Write("AuthorizationInfo.processSignedData: Nastala chyba pocas spracovania CAdES podpisu. Detail: " + ex.ToString());
        //            return null;
        //        }

        //        output += "</SignerInfo>";
        //    }

        //    return output;
        //}

        private static X509Certificate getTimeStampCert(TimeStampToken tsToken)
        {
            X509Certificate signerCert = null;

            if (tsToken != null)
            {
                Org.BouncyCastle.X509.Store.IX509Store x509Certs = tsToken.GetCertificates("Collection");

                System.Collections.ArrayList certs = new System.Collections.ArrayList(x509Certs.GetMatches(null));

                // nájdenie podpisového certifikátu tokenu v kolekcii
                foreach (X509Certificate cert in certs)
                {
                    // kontrola issuer name a seriového čísla
                    if (cert.IssuerDN.Equivalent(tsToken.SignerID.Issuer) &&
                        cert.SerialNumber.Equals(tsToken.SignerID.SerialNumber))
                    {
                        signerCert = cert;
                        break;
                    }
                }
            }

            return(signerCert);
        }
コード例 #3
0
ファイル: PKWriter.cs プロジェクト: blueskaie/PdfMaker
        static void SignManifest(ZipFile zipFile, byte[] manifestFileData, X509Certificate2 certificate)
        {
            var cert = DotNetUtilities.FromX509Certificate(certificate);

            var privateKey = DotNetUtilities.GetKeyPair(certificate.PrivateKey).Private;
            var generator  = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);

            var certList = new System.Collections.ArrayList();

            //var a1Cert = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleWWDRCA.cer"));
            //var a2Cert = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleIncRootCertificate.cer"));

            certList.Add(cert);
            //certList.Add(DotNetUtilities.FromX509Certificate(a1Cert));
            //certList.Add(DotNetUtilities.FromX509Certificate(a2Cert));

            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);

            generator.AddCertificates(st1);

            var content    = new CmsProcessableByteArray(manifestFileData);
            var signedData = generator.Generate(content, false);

            var data = signedData.GetEncoded();

            zipFile.AddEntry("signature", data);
        }
コード例 #4
0
        // https://github.com/joschi/cryptoworkshop-bouncycastle/blob/master/src/main/java/cwguide/BcSignedDataExample.java
        public static void foo()
        {
            byte[] data = null;
            Org.BouncyCastle.Cms.CmsSignedData signedData = new CmsSignedData(data);

            byte[] content = signedData.SignedContent.GetContent() as byte[];

            Org.BouncyCastle.X509.Store.IX509Store certs = signedData.GetCertificates("type");
        }
コード例 #5
0
ファイル: MainForm.cs プロジェクト: random9/SignPDF
        //  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);
            }
        }
コード例 #6
0
        // taken from bouncy castle SignedDataTest.cs
        private static bool VerifySignatures(CmsSignedData sp)
        {
            var signaturesValid = true;

            Org.BouncyCastle.X509.Store.IX509Store x509Certs = sp.GetCertificates("Collection");
            SignerInformationStore signers = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                Collections.ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                Collections.IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)certEnum.Current;

                signaturesValid &= signer.Verify(cert);
            }

            return(signaturesValid);
        }
コード例 #7
0
        public static byte[] FirmaFileBouncy(byte[] data, X509Certificate2 cert)
        {
            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
                CmsSignedData Firmato = cms.Generate(new CmsProcessableByteArray(data), false);

                CmsSigner cmsSigner = new CmsSigner(cert);
                cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

                System.Security.Cryptography.Pkcs.ContentInfo contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(Firmato.GetEncoded());
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(Firmato.GetEncoded());
                byte[] ret = signedCms.Encode();
                return(ret);
            }
            catch
            {
                return(null);
            }
        }
コード例 #8
0
ファイル: DSCUtils.cs プロジェクト: SadanSuddala/GSTN-Code
        public static byte[] SignBC(string text, X509Certificate2 cert)

        {
            Org.BouncyCastle.X509.X509Certificate          cert2 = DotNetUtilities.FromX509Certificate(cert);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter K     = DotNetUtilities.GetKeyPair(cert.PrivateKey).Private;
            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(K, cert2, CmsSignedDataGenerator.EncryptionRsa, CmsSignedDataGenerator.DigestSha256);

            List <Org.BouncyCastle.X509.X509Certificate> certList = new List <Org.BouncyCastle.X509.X509Certificate>();

            certList.Add(cert2);

            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);

            generator.AddCertificates(st1);
            byte[] data = Encoding.UTF8.GetBytes(text);

            CmsSignedData signedData = generator.Generate(new CmsProcessableByteArray(data), true);

            return(signedData.GetEncoded());
        }
コード例 #9
0
        /// <summary>
        /// Questo metodo verifica se l'associazione fra marca e file è valida, verifica inoltre la
        /// validità del certificato firmatario della marca e la data di scadenza della marca; infine
        /// restituisce (se le verifiche vanno a buon fine) tutti i dati contenuti nella marca.
        /// </summary>
        /// <param name="tsRes"></param>
        /// <param name="tsReq"></param>
        /// <returns></returns>
        protected OutputResponseMarca checkMarca(TimeStampResponse tsRes, TimeStampRequest tsReq)
        {
            OutputResponseMarca outTSR = new OutputResponseMarca();

            try
            {
                tsRes.Validate(tsReq);
                outTSR.esito             = "OK";
                outTSR.descrizioneErrore = string.Empty;
            }
            catch (TspException e)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "verifica della marca fallita: " + e.Message;
                logger.Debug("verifica della marca fallita: " + e.Message);
                //return outTSR;
            }

            TimeStampToken tsToken = tsRes.TimeStampToken;

            //Verifica data scadenza marca secondo l'ora locale
            Org.BouncyCastle.X509.Store.IX509Store store = tsToken.GetCertificates("Collection");
            Org.BouncyCastle.X509.X509Certificate  cert  = (Org.BouncyCastle.X509.X509Certificate) new ArrayList(store.GetMatches(tsToken.SignerID))[0];
            //se la data attuale è maggiore di quella di scadenza del certificato che ha firmato la marca
            //allora la marca è scaduta!!!
            if (DateTime.Now.CompareTo(cert.NotAfter.ToLocalTime()) > 0)
            {
                //outTSR.esito = "KO";
                outTSR.descrizioneErrore = "marca temporale scaduta";
                logger.Debug("marca temporale scaduta");
                //return outTSR;
            }

            try
            {
                //estrazione delle informazioni dalla marca
                outTSR.dsm            = cert.NotAfter.ToLocalTime().ToString();
                outTSR.sernum         = tsToken.TimeStampInfo.SerialNumber.ToString();
                outTSR.fhash          = byteArrayToHexa(tsToken.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage());
                outTSR.docm           = tsToken.TimeStampInfo.TstInfo.GenTime.TimeString;
                outTSR.docm_date      = tsToken.TimeStampInfo.GenTime.ToLocalTime().ToString();
                outTSR.marca          = Convert.ToBase64String(tsRes.GetEncoded());
                outTSR.algCertificato = cert.SigAlgName;
                outTSR.fromDate       = cert.NotBefore.ToLocalTime().ToString();
                outTSR.snCertificato  = cert.SerialNumber.ToString();
                //Algoritmo hash utilizzato per l'impronta
                string algHashOid = tsToken.TimeStampInfo.MessageImprintAlgOid;
                if (!string.IsNullOrEmpty(algHashOid))
                {
                    System.Security.Cryptography.Oid oidHash = new System.Security.Cryptography.Oid(algHashOid);
                    outTSR.algHash = oidHash.FriendlyName;
                }

                outTSR.TSA = new TSARFC2253();

                //Con le TSA di test potrebbe non essere valorizzato l'oggetto TSA
                logger.Debug("Controllo TSA : " + tsToken.TimeStampInfo.Tsa);
                try
                {
                    if (tsToken.TimeStampInfo.Tsa != null)
                    {
                        string oid      = string.Empty;
                        string oidValue = string.Empty;
                        logger.Debug("TagNo: " + tsToken.TimeStampInfo.Tsa.TagNo);
                        for (int n = 0; n < tsToken.TimeStampInfo.Tsa.TagNo; n++)
                        {
                            logger.Debug("Tag: " + n);
                            Org.BouncyCastle.Asn1.Asn1Sequence seq = (Org.BouncyCastle.Asn1.Asn1Sequence)tsToken.TimeStampInfo.Tsa.Name.ToAsn1Object();

                            //Obsoleto
                            //Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(n);
                            Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[n];

                            Org.BouncyCastle.Asn1.Asn1Set set1 = (Org.BouncyCastle.Asn1.Asn1Set)obj.ToAsn1Object();

                            //Obsoleto
                            //seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1.GetObjectAt(0);
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(0);
                            seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1[0];
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[0];


                            oid = obj.ToString();

                            //Obsoleto
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(1);
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[1];

                            oidValue = obj.ToString();
                            System.Security.Cryptography.Oid oid_obj = new System.Security.Cryptography.Oid(oid);
                            string friendly = oid_obj.FriendlyName;
                            logger.Debug("oid: " + oid + " friendly: " + friendly);
                            switch (friendly)
                            {
                            case "CN":
                                outTSR.TSA.CN = oidValue;
                                break;

                            case "OU":
                                outTSR.TSA.OU = oidValue;
                                break;

                            case "O":
                                outTSR.TSA.O = oidValue;
                                break;

                            case "C":
                                outTSR.TSA.C = oidValue;
                                break;
                            }
                        }
                        outTSR.TSA.TSARFC2253Name = "CN=" + outTSR.TSA.CN + ",OU=" + outTSR.TSA.OU + ",O=" + outTSR.TSA.O + ",C=" + outTSR.TSA.C;
                    }
                }
                catch (Exception e)
                {
                    logger.Debug("Eccezione controllo TSA : " + e.Message);
                }
                logger.Debug("Fine Controllo TSA");
            }
            catch (Exception eTsp)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "estrazione delle informazioni dalla marca fallita: " + eTsp.Message;
                logger.Debug("estrazione delle informazioni dalla marca fallita: " + eTsp.Message);
                //return outTSR;
            }

            //verifico l'esistenza del documento al quale è associata la marca temporale
            //Commentata perchè l'impronta del documento è ancora calcolata con SHA1 invece che SHA256
            //DocsPaDB.Query_DocsPAWS.Documenti documento = new DocsPaDB.Query_DocsPAWS.Documenti();
            //outTSR.timestampedDoc = documento.GetDocNumberByImpronta(outTSR.fhash);
            //if (string.IsNullOrEmpty(outTSR.timestampedDoc))
            //{
            //    outTSR.timestampedDoc = "Non esiste alcun documento associato alla marca temporale.";
            //}

            //costruisco l'oggetto rappresentante il contenuto in chiaro della marca
            outTSR.DecryptedTSR             = new Marca();
            outTSR.DecryptedTSR.content     = contentMarca(outTSR);
            outTSR.DecryptedTSR.contentType = "text/html"; //"application/x-html";
            outTSR.DecryptedTSR.length      = outTSR.DecryptedTSR.content.Length;

            return(outTSR);
        }
コード例 #10
0
ファイル: MainForm.cs プロジェクト: random9/SignPDF
        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);
            }
        }