예제 #1
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);
        }
예제 #2
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);
        }
예제 #3
0
        //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);
        }