Example usage for com.lowagie.text.pdf AcroFields verifySignature

List of usage examples for com.lowagie.text.pdf AcroFields verifySignature

Introduction

In this page you can find the example usage for com.lowagie.text.pdf AcroFields verifySignature.

Prototype

public PdfPKCS7 verifySignature(String name) 

Source Link

Document

Verifies a signature.

Usage

From source file:ec.gov.informatica.firmadigital.FirmaDigital.java

License:Open Source License

public List<String> verificar(String direccionPDF) throws SignatureVerificationException {
    try {/* w  w w  .j a  va 2s  .  c  o m*/
        List<String> firmantes = new ArrayList<>();
        if (direccionPDF == null || direccionPDF.isEmpty()) {
            System.out.print("Necesito el nombre del PDF a comprobar");
            System.exit(1);
        }

        Random rnd = new Random();
        KeyStore kall = PdfPKCS7.loadCacertsKeyStore();
        PdfReader reader = new PdfReader(direccionPDF);
        AcroFields af = reader.getAcroFields();
        ArrayList names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {

            String name = (String) names.get(k);
            //            System.out.println(name);
            int random = rnd.nextInt();
            FileOutputStream out = new FileOutputStream(
                    "revision_" + random + "_" + af.getRevision(name) + ".pdf");

            byte bb[] = new byte[8192];
            InputStream ip = af.extractRevision(name);
            int n = 0;
            while ((n = ip.read(bb)) > 0)
                out.write(bb, 0, n);
            out.close();
            ip.close();

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();
            Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
            String firmante = pk.getSignName() + " (" + name + ") - ";
            if (fails == null) {
                firmante += "Firma Verificada";
            } else {
                firmante += "Firma No Vlida";
            }
            File f = new File("revision_" + random + "_" + af.getRevision(name) + ".pdf");
            f.delete();
            firmantes.add(firmante);
        }
        return firmantes;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:es.gob.afirma.signers.pades.AOPDFSigner.java

License:Open Source License

/** Recupera el &aacute;rbol de nodos de firma de una firma electr&oacute;nica.
 * Los nodos del &aacute;rbol ser&aacute;n textos con el <i>CommonName</i> (CN X.500)
 * del titular del certificado u objetos de tipo AOSimpleSignInfo con la
 * informaci&oacute;n b&aacute;sica de las firmas individuales, seg&uacute;n
 * el valor del par&aacute;metro <code>asSimpleSignInfo</code>. Los nodos se
 * mostrar&aacute;n en el mismo orden y con la misma estructura con el que
 * aparecen en la firma electr&oacute;nica.<br>
 * La propia estructura de firma se considera el nodo ra&iacute;z, la firma y cofirmas
 * pender&aacute;n directamentede de este.
 * @param sign Firma electr&oacute;nica de la que se desea obtener la estructura.
 * @param asSimpleSignInfo/*  www.  j a  va 2s  .  com*/
 *        Si es <code>true</code> se devuelve un &aacute;rbol con la
 *        informaci&oacute;n b&aacute;sica de cada firma individual
 *        mediante objetos <code>AOSimpleSignInfo</code>, si es <code>false</code> un &aacute;rbol con los nombres (CN X.500) de los
 *        titulares certificados.
 * @return &Aacute;rbol de nodos de firma o <code>null</code> en caso de error. */
@Override
public AOTreeModel getSignersStructure(final byte[] sign, final boolean asSimpleSignInfo) {

    final AOTreeNode root = new AOTreeNode("Datos"); //$NON-NLS-1$

    if (!isPdfFile(sign)) {
        return new AOTreeModel(root);
    }

    PdfReader pdfReader;
    try {
        pdfReader = new PdfReader(sign);
    } catch (final BadPasswordException e) {
        try {
            pdfReader = new PdfReader(sign,
                    new String(AOUIFactory.getPassword(CommonPdfMessages.getString("AOPDFSigner.0"), //$NON-NLS-1$
                            null)).getBytes());
        } catch (final BadPasswordException e2) {
            LOGGER.severe("La contrasena del PDF no es valida, se devolvera un arbol vacio: " + e2); //$NON-NLS-1$
            return new AOTreeModel(root);
        } catch (final Exception e3) {
            LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e3); //$NON-NLS-1$
            return new AOTreeModel(root);
        }
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e); //$NON-NLS-1$
        return new AOTreeModel(root);
    }

    final AcroFields af;
    try {
        af = pdfReader.getAcroFields();
    } catch (final Exception e) {
        LOGGER.severe(
                "No se ha podido obtener la informacion de los firmantes del PDF, se devolvera un arbol vacio: " //$NON-NLS-1$
                        + e);
        return new AOTreeModel(root);
    }

    final List<String> names = af.getSignatureNames();
    Object pkcs1Object = null;
    for (int i = 0; i < names.size(); ++i) {
        final PdfPKCS7 pcks7;
        try {
            pcks7 = af.verifySignature(names.get(i).toString());
        } catch (final Exception e) {
            LOGGER.severe("El PDF contiene una firma corrupta o con un formato desconocido (" + //$NON-NLS-1$
                    names.get(i).toString() + "), se continua con las siguientes si las hubiese: " + e //$NON-NLS-1$
            );
            continue;
        }
        if (asSimpleSignInfo) {
            final AOSimpleSignInfo ssi = new AOSimpleSignInfo(
                    new X509Certificate[] { pcks7.getSigningCertificate() }, pcks7.getSignDate().getTime());

            // Extraemos el PKCS1 de la firma
            try {
                // iText antiguo
                final Field digestField = Class.forName("com.lowagie.text.pdf.PdfPKCS7") //$NON-NLS-1$
                        .getDeclaredField("digest"); //$NON-NLS-1$
                digestField.setAccessible(true);
                pkcs1Object = digestField.get(pcks7);
            } catch (final Exception e) {
                LOGGER.severe(
                        "No se ha podido obtener informacion de una de las firmas del PDF, se continuara con la siguiente: " //$NON-NLS-1$
                                + e);
                continue;
            }
            if (pkcs1Object instanceof byte[]) {
                ssi.setPkcs1((byte[]) pkcs1Object);
            }
            root.add(new AOTreeNode(ssi));
        } else {
            root.add(new AOTreeNode(AOUtil.getCN(pcks7.getSigningCertificate())));
        }
    }

    return new AOTreeModel(root);
}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*/*from  w w  w.  j a v a  2  s  .c o  m*/
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want the multiple signatures, the
             * signatures are appended sequentially to the end of the document. The recursive call helps to get the
             * signature from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFSignatureService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*/*from w w w. jav  a2s.com*/
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures are
             * appended sequentially to the end of the document. The recursive call help to get the signature from the
             * original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDictionary outerCatalog,
        SignatureValidationCallback callback, List<String> alreadyLoadedRevisions)
        throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*// ww w .ja  va 2 s. c  o  m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interrested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();

            PdfDictionary signatureDictionary = af.getSignatureDictionary(name);
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(reader, outerCatalog, pk.getSigningCertificate(),
                        cal != null ? cal.getTime() : null, pkc, signatureDictionary, pk);
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDictionary catalog = reader.getCatalog();

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures
             * are appended sequentially to the end of the document. The recursive call help to get the signature
             * from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:net.sf.jsignpdf.verify.VerifierLogic.java

License:Mozilla Public License

/**
 * Verifies signature(s) in PDF document.
 * //from w ww  .j a v  a2s  . co  m
 * @param tmpReader
 *            PdfReader for given PDF
 * @return
 */
@SuppressWarnings("unchecked")
private VerificationResult verify(final PdfReader tmpReader) {
    final VerificationResult tmpResult = new VerificationResult();
    try {
        final AcroFields tmpAcroFields = tmpReader.getAcroFields();
        final List<String> tmpNames = tmpAcroFields.getSignatureNames();
        tmpResult.setTotalRevisions(tmpAcroFields.getTotalRevisions());

        final int lastSignatureIdx = tmpNames.size() - 1;
        if (lastSignatureIdx < 0) {
            // there is no signature
            tmpResult.setWithoutSignature();
        }
        for (int i = lastSignatureIdx; i >= 0; i--) {
            final String name = tmpNames.get(i);
            final SignatureVerification tmpVerif = new SignatureVerification(name);
            tmpVerif.setLastSignature(i == lastSignatureIdx);
            tmpVerif.setWholeDocument(tmpAcroFields.signatureCoversWholeDocument(name));
            tmpVerif.setRevision(tmpAcroFields.getRevision(name));
            final PdfPKCS7 pk = tmpAcroFields.verifySignature(name);
            final TimeStampToken tst = pk.getTimeStampToken();
            tmpVerif.setTsTokenPresent(tst != null);
            tmpVerif.setTsTokenValidationResult(validateTimeStampToken(tst));
            tmpVerif.setDate(pk.getTimeStampDate() != null ? pk.getTimeStampDate() : pk.getSignDate());
            tmpVerif.setLocation(pk.getLocation());
            tmpVerif.setReason(pk.getReason());
            tmpVerif.setSignName(pk.getSignName());
            final Certificate pkc[] = pk.getCertificates();
            final X509Name tmpX509Name = PdfPKCS7.getSubjectFields(pk.getSigningCertificate());
            tmpVerif.setSubject(tmpX509Name.toString());
            tmpVerif.setModified(!pk.verify());
            tmpVerif.setOcspPresent(pk.getOcsp() != null);
            tmpVerif.setOcspValid(pk.isRevocationValid());
            tmpVerif.setCrlPresent(pk.getCRLs() != null && pk.getCRLs().size() > 0);
            tmpVerif.setFails(PdfPKCS7.verifyCertificates(pkc, kall, pk.getCRLs(), tmpVerif.getDate()));
            tmpVerif.setSigningCertificate(pk.getSigningCertificate());

            // generate CertPath
            List<Certificate> certList = Arrays.asList(pkc);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            CertPath cp = cf.generateCertPath(certList);
            tmpVerif.setCertPath(cp);

            // to save time - check OCSP in certificate only if document's OCSP is not present and valid
            if (!tmpVerif.isOcspValid()) {
                // try to get OCSP url from signing certificate 
                String url = PdfPKCS7.getOCSPURL((X509Certificate) pk.getSigningCertificate());
                tmpVerif.setOcspInCertPresent(url != null);

                if (url != null) {
                    // OCSP url is found in signing certificate - verify certificate with that url
                    tmpVerif.setOcspInCertValid(validateCertificateOCSP(pk.getSignCertificateChain(), url));
                }
            }

            String certificateAlias = kall.getCertificateAlias(pk.getSigningCertificate());
            if (certificateAlias != null) {
                // this means that signing certificate is directly trusted

                String verifyCertificate = PdfPKCS7.verifyCertificate(pk.getSigningCertificate(), pk.getCRLs(),
                        tmpVerif.getDate());
                if (verifyCertificate == null) {
                    // this means that signing certificate is valid
                    tmpVerif.setSignCertTrustedAndValid(true);
                }
            }

            final InputStream revision = tmpAcroFields.extractRevision(name);
            try {
                final PdfReader revisionReader = new PdfReader(revision);
                tmpVerif.setCertLevelCode(revisionReader.getCertificationLevel());
            } finally {
                if (revision != null) {
                    revision.close();
                }
            }
            tmpResult.addVerification(tmpVerif);
            if (failFast && tmpVerif.containsError()) {
                return tmpResult;
            }
        }
    } catch (Exception e) {
        tmpResult.setException(e);
    }
    return tmpResult;
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

protected List<X509Certificate> getCertificates(PdfReader pdfReader) throws SignException {
    List<X509Certificate> pdfCertificates = new ArrayList<X509Certificate>();
    AcroFields acroFields = pdfReader.getAcroFields();
    @SuppressWarnings("unchecked")
    List<String> signatureNames = acroFields.getSignatureNames();
    for (String signatureName : signatureNames) {
        PdfPKCS7 pdfPKCS7 = acroFields.verifySignature(signatureName);
        X509Certificate signingCertificate = pdfPKCS7.getSigningCertificate();
        pdfCertificates.add(signingCertificate);
    }/* www.  j a v  a  2 s.  c  om*/
    return pdfCertificates;
}

From source file:org.webpki.pdf.PDFVerifier.java

License:Apache License

public void verifyDocumentSignature(byte[] indoc) throws IOException {
    try {/* w w w  . j a v a2s.c  o  m*/
        PdfReader reader = new PdfReader(indoc);
        AcroFields af = reader.getAcroFields();
        ArrayList<?> names = af.getSignatureNames();
        for (int k = 0; k < names.size(); ++k) {
            String name = (String) names.get(k);
            whole_doc_signature = af.signatureCoversWholeDocument(name);
            if ((stop_on_index && k == stop_index) || (!stop_on_index && whole_doc_signature)) {
                signature_name = name;
                document_revision = af.getRevision(name);
                ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
                byte buffer[] = new byte[8192];
                InputStream ip = af.extractRevision(name);
                int n = 0;
                while ((n = ip.read(buffer)) > 0) {
                    bout.write(buffer, 0, n);
                }
                bout.close();
                ip.close();
                file_data = bout.toByteArray();
                PdfPKCS7 pk = af.verifySignature(name);
                signing_time = pk.getSignDate().getTime();
                X509Certificate pkc[] = (X509Certificate[]) pk.getCertificates();
                is_modified = !pk.verify();
                X509Certificate cert = pk.getSigningCertificate();
                for (int q = 0; q < pkc.length; q++) {
                    if (cert.equals(pkc[q])) {
                        verifier.verifyCertificatePath(CertificateUtil.getSortedPath(pkc));
                        return;
                    }
                }
                throw new IOException("Signature certificate not found in path");
            }
        }
        if (stop_on_index) {
            throw new IOException("Signature with index " + stop_index + " not found");
        }
        throw new IOException("No whole-document signature found");
    } catch (GeneralSecurityException gse) {
        throw new IOException(gse.getMessage());
    }
}

From source file:vn.vfossa.signature.PdfContent.java

License:Open Source License

@Override
public boolean validateSignatures() {
    // TODO Auto-generated method stub
    AcroFields af = content.getAcroFields();
    List<String> names = af.getSignatureNames();
    String name = names.get(0);//from w  w  w.j  a va  2 s  .c o m
    PdfPKCS7 pk = af.verifySignature(name);
    X509Certificate pkc[] = (X509Certificate[]) pk.getCertificates();
    Calendar calendar = pk.getTimeStampDate();
    String fails = PdfPKCS7.verifyCertificate(pkc[0], null, calendar);
    if (fails == null)
        return true;

    return false;
}