public string DecompressImage(string ImageValue)
        {
            Chilkat.Compression compress = new Chilkat.Compression();
            Chilkat.BinData     binDat   = new Chilkat.BinData();
            binDat.AppendEncoded(ImageValue, "base64");
            compress.DecompressBd(binDat);

            return(binDat.GetEncoded("base64"));
        }
        /// <summary>
        /// verifica la firma
        /// </summary>
        /// <param name="pathFileSign">documento firmato</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <returns>se true la verifica è avvenuta con successo</returns>
        public static bool VerificaFirma(string pathFileSign, ref string lastError)
        {
            bool success = false;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.BinData bd = new Chilkat.BinData();

                success = bd.LoadFile(pathFileSign);
                if (!success)
                {
                    lastError = "Errore a caricare il file";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

                // Verifica ed estrae il payload contenuto nel .p7m.
                success = crypt.OpaqueVerifyBd(bd);

                if (!success)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
        /// <summary>
        /// converte file tsr in formato tsd (RFC 5544)
        /// </summary>
        /// <param name="pathFileTsr">file tsr</param>
        /// <param name="pathFileSign">file firmato</param>
        /// <param name="pathFileTsd">file tsd creato</param>
        /// <param name="lastError">ultimo errore della funzionalità</param>
        /// <returns>true se la funzionalità ha avuto successo</returns>
        public static bool CreaTsd(string pathFileTsr, string pathFileSign, out string pathFileTsd, ref string lastError)
        {
            bool success = false;

            pathFileTsd = null;
            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }


                Chilkat.BinData bdTsr = new Chilkat.BinData();
                success = bdTsr.LoadFile(pathFileTsr);
                if (!success)
                {
                    lastError = "Errore nel caricare il file tsr!";
                    return(success);
                }

                // Carico il tsr in un oggetto ASN.1
                Chilkat.Asn asnTsr = new Chilkat.Asn();
                success = asnTsr.LoadEncoded(bdTsr.GetEncoded("base64"), "base64");
                if (!success)
                {
                    lastError = asnTsr.LastErrorText;
                    return(success);
                }

                // Prendo il timestamp nell'xml
                Chilkat.Xml xmlTsr = new Chilkat.Xml();
                xmlTsr.LoadXml(asnTsr.AsnToXml());

                // Il timestamp inizia in questo modo
                // Rimuovo la prima sub-tree

                //     <?xml version="1.0" encoding="utf-8"?>
                //     <sequence>
                //         <sequence>       <---- Remove this sub-tree.
                //             <int>00</int>
                //             <sequence>
                //                 <utf8>Operation Okay</utf8>
                //             </sequence>
                //         </sequence>
                //         <sequence>
                //             <oid>1.2.840.113549.1.7.2</oid>
                //             <contextSpecific tag="0" constructed="1">
                //             ...

                // Rimuovo la prima sub-tree..
                xmlTsr.RemoveChildByIndex(0);

                // Combiniamo il timestamp e il .p7m in un timestampData
                Chilkat.BinData bdContent = new Chilkat.BinData();
                success = bdContent.LoadFile(pathFileSign);
                if (!success)
                {
                    lastError = "Errore nel caricare il file p7m!";
                    return(success);
                }

                // Costruisco il TimeStampData.
                // Lo costruisco in XML e poi lo converto in ASN.1
                Chilkat.Xml xml = new Chilkat.Xml();
                xml.Tag = "sequence";
                xml.UpdateChildContent("oid", "1.2.840.113549.1.9.16.1.31");
                xml.UpdateAttrAt("contextSpecific", true, "tag", "0");
                xml.UpdateAttrAt("contextSpecific", true, "constructed", "1");
                xml.UpdateChildContent("contextSpecific|sequence|int", "01");
                xml.UpdateChildContent("contextSpecific|sequence|octets", bdContent.GetEncoded("base64"));
                xml.UpdateAttrAt("contextSpecific|sequence|contextSpecific", true, "tag", "0");
                xml.UpdateAttrAt("contextSpecific|sequence|contextSpecific", true, "constructed", "1");

                Chilkat.Xml xContext = xml.GetChildWithTag("contextSpecific|sequence|contextSpecific");
                xContext.AddChildTree(xmlTsr);

                // Converto il file XML in ASN.1
                Chilkat.Asn tsd = new Chilkat.Asn();
                tsd.LoadAsnXml(xml.GetXml());

                // scrivo il timestamped
                success = tsd.WriteBinaryDer(pathFileTsd);
            }
            catch
            {
                throw;
            }

            return(success);
        }
        /// <summary>
        /// applica la marca temporale al file
        /// </summary>
        /// <param name="pathFileSign">file firmato</param>
        /// <param name="tsaUrl">url TSA</param>
        /// <param name="pathFileTimeStamped">file tsr da TSA</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <param name="userName">user TSA (opzionale)</param>
        /// <param name="password">password TSA (opzionale)</param>
        /// <returns>true se la funzionalità ha avuto successo</returns>
        /// <example>
        ///  if (Utilities.MarcaTemporale(@"c:\temp\IT01234567890_FPA01.xml.p7m", "https://freetsa.org/tsr", out pathFileTimeStamped, ref lastError, "myUser", "myPassword"))
        ///  {
        ///       pathFileTimeStamped -> c:\temp\IT01234567890_FPA01.xml.p7m.tsr
        ///  }
        /// </example>
        public static bool MarcaTemporale(string pathFileSign, string tsaUrl, out string pathFileTimeStamped, ref string lastError, string userName = null, string password = null)
        {
            bool success = false;

            pathFileTimeStamped = null;
            try
            {
                string fileName = Path.GetFileName(pathFileSign);



                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
                crypt.HashAlgorithm = "sha256";
                crypt.EncodingMode  = "base64";

                string base64Hash = crypt.HashFileENC(pathFileSign);

                Chilkat.Http http = new Chilkat.Http();

                Chilkat.BinData requestToken      = new Chilkat.BinData();
                string          optionalPolicyOid = string.Empty;
                bool            addNonce          = false;
                bool            requestTsaCert    = false;

                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                {
                    http.Login     = userName;
                    http.Password  = password;
                    http.BasicAuth = true;
                }

                //  Create a time-stamp request token
                success = http.CreateTimestampRequest("sha256", base64Hash, optionalPolicyOid, addNonce, requestTsaCert, requestToken);
                if (!success)
                {
                    lastError = http.LastErrorText;
                    return(success);
                }


                Chilkat.HttpResponse resp = http.PBinaryBd("POST", tsaUrl, requestToken, "application/timestamp-query", false, false);
                if (!http.LastMethodSuccess)
                {
                    lastError = http.LastErrorText;
                    return(success);
                }


                Chilkat.BinData timestampReply = new Chilkat.BinData();
                resp.GetBodyBd(timestampReply);
                if (!timestampReply.LastMethodSuccess)
                {
                    return(success);
                }


                string s = Path.ChangeExtension(fileName, $".{Enum.GetName(typeof(EstensioniFile), EstensioniFile.tsr)}");
                success = timestampReply.WriteFile(s);
                if (success)
                {
                    pathFileTimeStamped = s;
                }
            }
            catch
            {
                throw;
            }

            return(success);
        }