Esempio n. 1
0
        /**
         * Switches to the previous revision.
         * @throws IOException
         * @throws GeneralSecurityException
         */
        virtual public void SwitchToPreviousRevision()
        {
            LOGGER.Info("Switching to previous revision.");
            latestRevision = false;
            dss            = reader.Catalog.GetAsDict(PdfName.DSS);
            DateTime cal = pkcs7.TimeStampDate;

            if (cal == DateTime.MaxValue)
            {
                cal = pkcs7.SignDate;
            }
            // TODO: get date from signature
            signDate = cal;
            List <String> names = fields.GetSignatureNames();

            if (names.Count > 1)
            {
                signatureName = names[names.Count - 2];
                reader        = new PdfReader(fields.ExtractRevision(signatureName));
                fields        = reader.AcroFields;
                names         = fields.GetSignatureNames();
                signatureName = names[names.Count - 1];
                pkcs7         = CoversWholeDocument();
                LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
            }
            else
            {
                LOGGER.Info("No signatures in revision");
                pkcs7 = null;
            }
        }
Esempio n. 2
0
        /**
         * Creates a VerificationData object for a PdfReader
         * @param reader	a reader for the document we want to verify.
         * @throws GeneralSecurityException
         */
        public LtvVerifier(PdfReader reader) : base(null)
        {
            this.reader = reader;
            fields      = reader.AcroFields;
            List <String> names = fields.GetSignatureNames();

            signatureName = names[names.Count - 1];
            signDate      = DateTime.Now;
            pkcs7         = CoversWholeDocument();
            LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
        }
        /**
         * Checks if the signature covers the whole document
         * and throws an exception if the document was altered
         * @return a PdfPKCS7 object
         * @throws GeneralSecurityException
         */
        virtual protected PdfPKCS7 CoversWholeDocument()
        {
            PdfPKCS7 pkcs7 = fields.VerifySignature(signatureName);

            if (fields.SignatureCoversWholeDocument(signatureName))
            {
                LOGGER.Info("The timestamp covers whole document.");
            }
            else
            {
                throw new VerificationException(null, "Signature doesn't cover whole document.");
            }
            if (pkcs7.Verify())
            {
                LOGGER.Info("The signed document has not been modified.");
                return(pkcs7);
            }
            throw new VerificationException(null, "The document was altered after the signature was applied.");
        }
Esempio n. 4
0
	    /**
	     * Creates a VerificationData object for a PdfReader
	     * @param reader	a reader for the document we want to verify.
	     * @throws GeneralSecurityException 
	     */
	    public LtvVerifier(PdfReader reader) : base(null) {
		    this.reader = reader;
		    fields = reader.AcroFields;
		    List<String> names = fields.GetSignatureNames();
		    signatureName = names[names.Count - 1];
		    signDate = DateTime.Now;
		    pkcs7 = CoversWholeDocument();
		    LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
	    }
Esempio n. 5
0
	    /**
	     * Switches to the previous revision.
	     * @throws IOException
	     * @throws GeneralSecurityException 
	     */
	    virtual public void SwitchToPreviousRevision() {
		    LOGGER.Info("Switching to previous revision.");
		    latestRevision = false;
		    dss = reader.Catalog.GetAsDict(PdfName.DSS);
		    DateTime cal = pkcs7.TimeStampDate;
		    if (cal == DateTime.MaxValue)
			    cal = pkcs7.SignDate;
		    // TODO: get date from signature
	        signDate = cal;
		    List<String> names = fields.GetSignatureNames();
		    if (names.Count > 1) {
			    signatureName = names[names.Count - 2];
			    reader = new PdfReader(fields.ExtractRevision(signatureName));
			    fields = reader.AcroFields;
			    names = fields.GetSignatureNames();
			    signatureName = names[names.Count - 1];
			    pkcs7 = CoversWholeDocument();
			    LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName));
		    }
		    else {
			    LOGGER.Info("No signatures in revision");
			    pkcs7 = null;
		    }
	    }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException 
         * @throws IOException 
         * @throws GeneralSecurityException 
         * @throws NoSuchAlgorithmException 
         * @throws Exception 
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection<X509Certificate> chain, ICollection<ICrlClient> crlList, IOcspClient ocspClient,
                ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) {
            List<X509Certificate> certa = new List<X509Certificate>(chain);
            ICollection<byte[]> crlBytes = null;
            int i = 0;
            while (crlBytes == null && i < certa.Count)
        	    crlBytes = ProcessCrl(certa[i++], crlList);
            if (estimatedSize == 0) {
                estimatedSize = 8192;
                if (crlBytes != null) {
                    foreach (byte[] element in crlBytes) {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                    estimatedSize += 4192;
                if (tsaClient != null)
                    estimatedSize += 4192;
            }
            sap.Certificate = certa[0];
            if(sigtype == CryptoStandard.CADES)
                sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2);
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);
            dic.Reason = sap.Reason;
            dic.Location = sap.Location;
            dic.SignatureCreator = sap.SignatureCreator;
            dic.Contact = sap.Contact;
            dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            sap.CryptoDictionary = dic;

            Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
            exc[PdfName.CONTENTS] = estimatedSize * 2 + 2;
            sap.PreClose(exc);

            String hashAlgorithm = externalSignature.GetHashAlgorithm();
            PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false);
            IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream data = sap.GetRangeStream();
            byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm);
            DateTime cal = DateTime.Now;
            byte[] ocsp = null;
            if (chain.Count >= 2 && ocspClient != null) {
                ocsp = ocspClient.GetEncoded(certa[0], certa[1], null);
            }
            byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
            byte[] extSignature = externalSignature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());

            byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype);

            if (estimatedSize < encodedSig.Length)
                throw new IOException("Not enough space");

            byte[] paddedSig = new byte[estimatedSize];
            System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);

            PdfDictionary dic2 = new PdfDictionary();
            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
        /**
         * Signs the document using the detached mode, CMS or CAdES equivalent.
         * @param sap the PdfSignatureAppearance
         * @param externalSignature the interface providing the actual signing
         * @param chain the certificate chain
         * @param crlList the CRL list
         * @param ocspClient the OCSP client
         * @param tsaClient the Timestamp client
         * @param provider the provider or null
         * @param estimatedSize the reserved size for the signature. It will be estimated if 0
         * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS
         * @throws DocumentException
         * @throws IOException
         * @throws GeneralSecurityException
         * @throws NoSuchAlgorithmException
         * @throws Exception
         */
        public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient,
                                        ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
        {
            List <X509Certificate> certa    = new List <X509Certificate>(chain);
            ICollection <byte[]>   crlBytes = null;
            int i = 0;

            while (crlBytes == null && i < certa.Count)
            {
                crlBytes = ProcessCrl(certa[i++], crlList);
            }
            if (estimatedSize == 0)
            {
                estimatedSize = 8192;
                if (crlBytes != null)
                {
                    foreach (byte[] element in crlBytes)
                    {
                        estimatedSize += element.Length + 10;
                    }
                }
                if (ocspClient != null)
                {
                    estimatedSize += 4192;
                }
                if (tsaClient != null)
                {
                    estimatedSize += 4192;
                }
            }
            sap.Certificate = certa[0];
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);

            dic.Reason           = sap.Reason;
            dic.Location         = sap.Location;
            dic.Contact          = sap.Contact;
            dic.Date             = new PdfDate(sap.SignDate); // time-stamp will over-rule this
            sap.CryptoDictionary = dic;

            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = estimatedSize * 2 + 2;
            sap.PreClose(exc);

            String   hashAlgorithm = externalSignature.GetHashAlgorithm();
            PdfPKCS7 sgn           = new PdfPKCS7(null, chain, hashAlgorithm, false);
            IDigest  messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream   data          = sap.GetRangeStream();

            byte[]   hash = DigestAlgorithms.Digest(data, hashAlgorithm);
            DateTime cal  = DateTime.Now;

            byte[] ocsp = null;
            if (chain.Count >= 2 && ocspClient != null)
            {
                ocsp = ocspClient.GetEncoded(certa[0], certa[1], null);
            }
            byte[] sh           = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
            byte[] extSignature = externalSignature.Sign(sh);
            sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());

            byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype);

            if (estimatedSize + 2 < encodedSig.Length)
            {
                throw new IOException("Not enough space");
            }

            byte[] paddedSig = new byte[estimatedSize];
            System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);

            PdfDictionary dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            sap.Close(dic2);
        }
Esempio n. 8
0
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            LOGGER.Info("Adding verification for " + signatureName);
            X509Certificate[] xc = pk.Certificates;
            X509Certificate   cert;
            X509Certificate   signingCert = pk.SigningCertificate;
            ValidationData    vd          = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                cert = xc[k];
                LOGGER.Info("Certificate: " + cert.SubjectDN);
                if (certOption == CertificateOption.SIGNING_CERTIFICATE &&
                    !cert.Equals(signingCert))
                {
                    continue;
                }
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL)
                {
                    ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                        LOGGER.Info("OCSP added");
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded(xc[k], null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (Arrays.AreEqual(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                                LOGGER.Info("CRL added");
                            }
                        }
                    }
                }
                if (certInclude == CertificateInclusion.YES)
                {
                    vd.certs.Add(xc[k].GetEncoded());
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }
Esempio n. 9
0
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            X509Certificate[] xc = pk.SignCertificateChain;
            ValidationData    vd = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL && k < xc.Length - 1)
                {
                    ocspEnc = ocsp.GetEncoded(xc[k], xc[k + 1], null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded((X509Certificate)xc[k], null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (Arrays.AreEqual(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                            }
                        }
                    }
                }
                if (certOption == CertificateOption.SIGNING_CERTIFICATE)
                {
                    break;
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            if (certInclude == CertificateInclusion.YES)
            {
                foreach (X509Certificate c in xc)
                {
                    vd.certs.Add(c.GetEncoded());
                }
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }
Esempio n. 10
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;
            }
        }