コード例 #1
0
        /// <summary>
        /// Valida arquivos Office geral
        /// </summary>
        /// <param name="filePath">Caminho do arquivo a ser validado</param>
        /// <param name="format">Formato do documento a ser validado</param>
        /// <param name="onlyRoot">
        /// Determina se irá considerar apenas certificados de Autoridades Certificadoras.
        /// True: Considera apenas certificados de Autoridades Certificadoras.
        /// False: Considera todos os certificados instalados na máquina.
        /// Default: True.
        /// </param>
        /// <returns>Lista de assinaturas, válidas ou não</returns>
        internal static SignatureList validate(string filePath, FileFormat format, bool onlyRoot = true)
        {
            try
            {
                // list to return
                SignatureList list = new SignatureList();

                // open the file
                Package package;
                try
                {
                    package = Package.Open(filePath, FileMode.Open, FileAccess.Read);
                }
                catch (NullReferenceException e)
                {
                    throw new NullReferenceException(e.Message, e.InnerException);
                }

                // get the signatures
                PackageDigitalSignatureManager _dsm = new PackageDigitalSignatureManager(package);
                _dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

                // if no signatures found
                if (_dsm.Signatures == null || _dsm.Signatures.Count == 0)
                {
                    throw new NoSignatureFoundException();
                }

                // verify all the signatures
                foreach (PackageDigitalSignature signature in _dsm.Signatures)
                {
                    list.Add
                    (
                        new Signature
                        (
                            filePath,                                                      // file path
                            format,                                                        // file format
                            getObjective(signature.Signature.GetXml().OuterXml),           // objective
                            getSubject(signature.Signer.Subject),                          // subject
                            signature.SigningTime,                                         // date time
                            validateCertificate((X509Certificate2)signature.Signer, true), // validate the certificate
                            getCertificates((X509Certificate2)signature.Signer, true)      // certificate
                        )
                    {
                        SX509Certificate = (X509Certificate2)signature.Signer,
                        SFileProperties  = getFileProperties(package.PackageProperties)
                    }
                    );
                }

                // close the file
                package.Close();

                return(list);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #2
0
        /// <summary>
        /// Faz a conversão entre List<Signture> e SignatureList
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        private static SignatureList fromList(List <Signature> from)
        {
            SignatureList ret = new SignatureList();

            foreach (Signature item in from)
            {
                ret.Add(item);
            }

            return(ret);
        }
コード例 #3
0
        /// <summary>
        /// Valida arquivos XPS
        /// </summary>
        /// <param name="filePath">Caminho do arquivo a ser validado</param>
        /// <param name="onlyRoot">
        /// Determina se irá considerar apenas certificados de Autoridades Certificadoras.
        /// True: Considera apenas certificados de Autoridades Certificadoras.
        /// False: Considera todos os certificados instalados na máquina.
        /// Default: True.
        /// </param>
        /// <returns>Lista de assinaturas, válidas ou não</returns>
        internal static SignatureList validateXps(string filePath, bool onlyRoot = true)
        {
            SignatureList list = new SignatureList();

            // open the file
            XpsDocument xpsDocument = new XpsDocument(filePath, FileAccess.Read);

            if (xpsDocument.Signatures == null || xpsDocument.Signatures.Count == 0)
            {
                throw new NoSignatureFoundException();
            }

            foreach (XpsDigitalSignature digitalSignature in xpsDocument.Signatures)
            {
                list.Add
                (
                    new Signature
                    (
                        filePath,
                        FileFormat.XpsDocument,
                        null,
                        getSubject(digitalSignature.SignerCertificate.Subject),
                        digitalSignature.SigningTime,
                        digitalSignature.VerifyCertificate() == X509ChainStatusFlags.NoError,
                        getCertificates((X509Certificate2)digitalSignature.SignerCertificate, true)
                    )
                {
                    SX509Certificate = (X509Certificate2)digitalSignature.SignerCertificate,
                    SFileProperties  = getFileProperties(xpsDocument.CoreDocumentProperties)
                }
                );
            }

            xpsDocument.Close();

            return(list);
        }
コード例 #4
0
 /// <summary>
 /// Verifica se duas listas de assinaturas são iguais
 /// </summary>
 /// <param name="list1"></param>
 /// <param name="list2"></param>
 /// <returns></returns>
 public static bool ListsAreEqual(SignatureList list1, SignatureList list2)
 {
     return(list1.ToString() == list2.ToString());
 }
コード例 #5
0
        /// <summary>
        /// Valida arquivos PDF
        /// </summary>
        /// <param name="filePath">Caminho do arquivo a ser validado</param>
        /// <param name="onlyRoot">
        /// Determina se irá considerar apenas certificados de Autoridades Certificadoras.
        /// True: Considera apenas certificados de Autoridades Certificadoras.
        /// False: Considera todos os certificados instalados na máquina.
        /// Default: True.
        /// </param>
        /// <returns>Lista de assinaturas, válidas ou não</returns>
        internal static SignatureList validate(string filePath, bool onlyRoot = true)
        {
            try
            {
                #region [obsolete code]

                /*
                 *
                 * // list of valid certificates
                 * List<BCX.X509Certificate> kall = new List<BCX.X509Certificate>();
                 *
                 * // get the root certificates
                 * getSystemCertificates(StoreName.Root, StoreLocation.CurrentUser, ref kall);
                 *
                 * // if not only root, get others certificates
                 * if (!onlyRoot)
                 * {
                 *  getSystemCertificates(StoreName.AddressBook, StoreLocation.CurrentUser, ref kall);
                 *  getSystemCertificates(StoreName.AuthRoot, StoreLocation.CurrentUser, ref kall);
                 *  getSystemCertificates(StoreName.CertificateAuthority, StoreLocation.CurrentUser, ref kall);
                 *  getSystemCertificates(StoreName.My, StoreLocation.CurrentUser, ref kall);
                 *  getSystemCertificates(StoreName.TrustedPeople, StoreLocation.CurrentUser, ref kall);
                 *  getSystemCertificates(StoreName.TrustedPublisher, StoreLocation.CurrentUser, ref kall);
                 * }
                 * */
                #endregion

                // open the pdf file
                TS.PdfReader reader = new TS.PdfReader(filePath);

                // get the fields inside the file
                TS.AcroFields af = reader.AcroFields;

                // get the signatures
                List <string> names = af.GetSignatureNames();

                // if don't found signature
                if (names == null || names.Count == 0)
                {
                    throw new NoSignatureFoundException();
                }

                // signatures to return
                SignatureList signatures = new SignatureList();

                // for each signature in pdf file
                foreach (string name in names)
                {
                    // verify the signature
                    TSS.PdfPKCS7 pk = af.VerifySignature(name);

                    // get the datetime of signature
                    DateTime cal = pk.SignDate;
                    cal = (pk.TimeStampToken != null ? pk.TimeStampDate : cal);

                    // create the signature
                    Signature sig = new Signature
                                    (
                        filePath,                                    // file path
                        FileFormat.PDFDocument,                      // pdf format
                        pk.Reason,                                   // objective
                        getSubject(pk.SigningCertificate.SubjectDN), // subject
                        cal,                                         // date time
                        //verifySignature(pk.SignCertificateChain, kall, cal, pk.SigningCertificate), // signature validate, obsolete
                        verifySignature(pk.SigningCertificate),
                        getSignatureCertificates(pk.SignCertificateChain)     // get the certificates
                                    );

                    // set the x509certificates
                    sig.SX509Certificate = convertCertificate(pk.SigningCertificate);

                    // set the issuer
                    sig.SIssuer = pk.SigningCertificate.IssuerDN.ToString();

                    // set the file properties
                    foreach (KeyValuePair <string, string> prop in reader.Info)
                    {
                        FileProperties?fp = null;
                        try
                        {
                            fp = (FileProperties)Enum.Parse(typeof(FileProperties), prop.Key, true);
                        }
                        catch { }

                        if (fp.HasValue)
                        {
                            sig.addProperties(fp.Value, prop.Value);
                        }
                    }

                    // add signature to the list
                    signatures.Add(sig);
                }

                return(signatures);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }