Example usage for com.lowagie.text.pdf PdfPKCS7 verifyCertificates

List of usage examples for com.lowagie.text.pdf PdfPKCS7 verifyCertificates

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPKCS7 verifyCertificates.

Prototype

public static Object[] verifyCertificates(Certificate certs[], KeyStore keystore, Collection crls,
        Calendar calendar) 

Source Link

Document

Verifies a certificate chain against a KeyStore.

Usage

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

License:Open Source License

public List<String> verificar(String direccionPDF) throws SignatureVerificationException {
    try {/*  ww  w .j  ava 2  s. c  om*/
        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:net.sf.jsignpdf.verify.VerifierLogic.java

License:Mozilla Public License

/**
 * Verifies signature(s) in PDF document.
 * //from  w  w  w . j a v  a  2  s . com
 * @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:net.sf.jsignpdf.verify.VerifierLogic.java

License:Mozilla Public License

public Exception validateTimeStampToken(TimeStampToken token) {
    if (token == null) {
        return null;
    }//ww w.ja v  a2 s. com
    try {
        SignerId signer = token.getSID();

        X509Certificate certificate = null;
        X500Principal sign_cert_issuer = signer.getIssuer();
        BigInteger sign_cert_serial = signer.getSerialNumber();

        CertStore store = token.getCertificatesAndCRLs("Collection", "BC");

        // Iterate CertStore to find a signing certificate
        Collection<? extends Certificate> certs = store.getCertificates(null);
        Iterator<? extends Certificate> iter = certs.iterator();

        while (iter.hasNext()) {
            X509Certificate cert = (X509Certificate) iter.next();
            if (cert.getIssuerX500Principal().equals(sign_cert_issuer)
                    && cert.getSerialNumber().equals(sign_cert_serial)) {
                certificate = cert;
                break;
            }
        }

        if (certificate == null) {
            throw new TSPException("Missing signing certificate for TSA.");
        }

        // check TS token's certificate against keystore
        if (certs.size() == 1) {
            boolean verifyTimestampCertificates = PdfPKCS7.verifyTimestampCertificates(token, kall, null);
            if (!verifyTimestampCertificates) {
                throw new Exception("Timestamp certificate can't be verified.");
            }
        } else {
            int certSize = certs.size();
            Certificate[] array = certs.toArray(new Certificate[certSize]);
            Certificate[] certArray = new Certificate[certSize];
            // reverse order
            for (int i = 0; i < certSize; i++) {
                certArray[i] = array[certSize - 1 - i];
            }
            // token.validate(SignerInformationVerifier) will check if certificate has been valid at the time the timestamp was created
            Object[] verifyCertificates = PdfPKCS7.verifyCertificates(certArray, kall, null, null);
            if (verifyCertificates != null) {
                throw new Exception("Timestamp certificate can't be verified.");
            }
        }

        SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().build(certificate);
        token.validate(verifier);
    } catch (Exception e) {
        return e;
    }
    return null;
}