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

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

Introduction

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

Prototype

public PdfPKCS7 verifySignature(String name) 

Source Link

Document

Verifies a signature.

Usage

From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java

License:Open Source License

private Signature display(AcroFields fields, String name) {
    // digitalsignatures20130304.pdf : Code sample 5.2
    to.println(String.format("Signature covers the whole document: %s",
            (fields.signatureCoversWholeDocument(name) ? "Yes" : "No")));
    to.println(/*from   w  ww  .j av a 2 s.  c  om*/
            String.format("Document revision: %d of %d", fields.getRevision(name), fields.getTotalRevisions()));

    PdfPKCS7 pkcs7 = fields.verifySignature(name);
    Signature signature = display(pkcs7);
    signature.coversWholeDocument = fields.signatureCoversWholeDocument(name);
    signature.revision = fields.getRevision(name);
    return signature;
}

From source file:de.rub.dez6a3.jpdfsigner.control.ITextPDFSignatureVerifier.java

License:Open Source License

public void verifySignature(PdfReader reader, KeyStore ks) throws VerifySignatureException {
    issuerName = null;//  w  w  w.j av a 2s.  c om
    signedForName = null;
    boolean result = true;
    List<X509Certificate[]> validatedChainCerts = new ArrayList<X509Certificate[]>();

    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();
    if (names.size() < 1) {
        GlobalData.setSignerChain(null);
        throw new VerifySignatureException("PDF doesn't contain a signature");
    }

    for (String currName : names) {
        log.info("-------------Reading following Documentsignature: " + currName + "------------------");
        log.info("Signature name: " + currName);
        log.info("Signature covers whole document: " + af.signatureCoversWholeDocument(currName));
        log.info("Current Documentrevision: " + af.getRevision(currName));
        PdfPKCS7 pkcs7 = af.verifySignature(currName);
        log.info("Building whole chain ...");
        Certificate[] certs = pkcs7.getSignCertificateChain(); //Um zu berprfen ob alle Certs auch X509Certificate - typen sind
        X509Certificate[] validatedX509Certs = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            Certificate currCert = certs[i];
            if (currCert instanceof X509Certificate) {
                if (issuerName == null && af.getRevision(currName) == 1) {
                    issuerName = PdfPKCS7.getSubjectFields((X509Certificate) currCert).getField("CN");

                }
                try {
                    String[] reasonField = pkcs7.getReason().split(":");
                    if (reasonField[0].trim().equals("Signature Userid")) {
                        if (signedForName == null) {
                            signedForName = reasonField[1].trim();
                        }
                    }
                } catch (Exception e) {
                }
                log.info("Adding certificate with following CN to chain: "
                        + PdfPKCS7.getSubjectFields((X509Certificate) currCert).getField("CN"));
                validatedX509Certs[i] = (X509Certificate) currCert;
            } else {
                log.error("Certificate must be instance of X509Certificate... The verification will fail!");
                result = false;
            }
        }
        validatedChainCerts.add(validatedX509Certs);
        X509Certificate[] pdfCerts = (X509Certificate[]) pkcs7.getCertificates();
        ArrayList<X509Certificate> pdfCertList = new ArrayList<X509Certificate>();
        for (X509Certificate pdfCert : pdfCerts) {
            pdfCertList.add(pdfCert);
        }

        try {
            log.info("Timestamp is NOT verified! Will be implemented soon!");
        } catch (NullPointerException e) {
            log.info("No timestamp found! Signature contains the date of the signers pc.");
        } catch (Exception e) {
            log.error(e);
        }
        Object fails[] = PdfPKCS7.verifyCertificates(
                pdfCertList.toArray(new X509Certificate[pdfCertList.size()]), ks, null, pkcs7.getSignDate());
        if (fails == null) {
            log.info("Certification verification succeeded: " + currName);
        } else {
            result = false;
            log.info("Certificate verification failed: " + fails[1]);
        }
        log.info("--------------------------------------");
    }
    GlobalData.setSignerChain(validatedChainCerts);

    if (!result) {
        throw new VerifySignatureException("At least one signature is invalid.");
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

/**
 * TODO: Mas de dos firmas?//ww  w.java2 s.c o  m
 * 
 * @param pdf
 * @throws IOException
 * @throws SignatureException
 */
public static boolean verificar(byte[] pdf) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(pdf);
    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();

    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        System.out.println("Signature name: " + name);
        System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

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

        if (ts != null) {
            cal = pk.getTimeStampDate();
        }

        if (!pk.isTsp() && ts != null) {
            boolean impr;
            try {
                impr = pk.verifyTimestampImprint();
                System.out.println("Timestamp imprint verifies: " + impr);
                System.out.println("Timestamp date: " + cal);
            } catch (NoSuchAlgorithmException e) {
                throw new SignatureException(e);
            }
        }

        System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
        System.out.println("Document modified: " + !pk.verify());

        KeyStore kall = KeyStoreUtil.loadCacertsKeyStore();

        Object fails[] = CertificateVerification.verifyCertificates(pkc, kall, null, cal);

        if (fails == null) {
            System.out.println("Certificates verified against the KeyStore");
        } else {
            System.out.println("Certificate failed: " + fails[0]);
            return false;
        }

        BasicOCSPResp ocsp = pk.getOcsp();

        if (ocsp != null) {
            try {
                X509Certificate cert = new SecurityDataSubCaCert();

                boolean verifies = ocsp.isSignatureValid(new JcaContentVerifierProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert.getPublicKey()));

                System.out.println("OCSP signature verifies: " + verifies);

                System.out.println("OCSP revocation refers to this certificate: " + pk.isRevocationValid());

                return verifies;
            } catch (OperatorCreationException e) {
                throw new SignatureException(e);
            } catch (OCSPException e) {
                throw new SignatureException(e);
            }
        } else {
            return true;
        }
    }

    return false;
}

From source file:hr.tstrelar.pdfsigcheck.helpers.DocumentRevision.java

License:Open Source License

protected DocumentRevision(AcroFields af, KeyStore kall, String signatureName) {
    this.af = af;
    this.kall = kall;
    this.signatureName = signatureName;
    pk = af.verifySignature(signatureName);

}

From source file:org.dihedron.crypto.operations.verify.pdf.PDFVerifier.java

License:Open Source License

@Override
public boolean verify(byte[] signed, byte[] data) throws CryptoException {
    boolean verified = false;
    try {//from   w ww .  j  av a  2  s.  c  om
        PdfReader reader = new PdfReader(signed);
        AcroFields af = reader.getAcroFields();
        ArrayList<String> names = af.getSignatureNames();
        for (String name : names) {
            logger.debug("signature name: {}", name);
            logger.debug("signature covers whole document: {}", af.signatureCoversWholeDocument(name));
            logger.debug("document revision: {} of {}", af.getRevision(name), af.getTotalRevisions());
            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate[] pkc = pk.getCertificates();
            logger.debug("subject: {}", PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
            logger.debug("revision modified: {}", !pk.verify());
            Object fails[] = PdfPKCS7.verifyCertificates(pkc, keyring.getKeyStore(), null, cal);
            if (fails == null) {
                logger.debug("certificates verified against the KeyStoreHelper");
                verified = true;
            } else {
                logger.warn("certificate failed: {}", fails[1]);
                verified = false;
            }
        }
    } catch (IOException e) {
        throw new CryptoException("I/O exception while verifying the signature", e);
    } catch (SignatureException e) {
        throw new CryptoException("Signature exception while verifying the signature", e);
    }
    return verified;
}

From source file:org.opencps.pki.PdfVerifier.java

License:Open Source License

/**
 * (non-Javadoc)/*ww  w.ja  v  a 2  s. co  m*/
 * @see org.opencps.pki.Verifier#getSignatureInfo()
 */
public List<SignatureInfo> getSignatureInfo(InputStream inputStream) {
    List<SignatureInfo> list = new ArrayList<SignatureInfo>();
    try {
        PdfReader reader = new PdfReader(inputStream);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> names = fields.getSignatureNames();
        for (String name : names) {
            PdfPKCS7 pkcs7 = fields.verifySignature(name);
            list.add(new PdfSignatureInfo(pkcs7));
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return list;
}

From source file:org.opencps.pki.PdfVerifier.java

License:Open Source License

/**
 * (non-Javadoc)/*from   w w  w  .j  a  va2 s .c o  m*/
 * @throws SignatureException 
 * @see org.opencps.pki.Verifier#verifySignature()
 */
public Boolean verifySignature(InputStream inputStream, KeyStore ks) throws SignatureException {
    Boolean verified = false;
    try {
        PdfReader reader = new PdfReader(inputStream);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> names = fields.getSignatureNames();
        for (String name : names) {
            PdfPKCS7 pkcs7 = fields.verifySignature(name);
            if (pkcs7.verify()) {
                Certificate[] certs = pkcs7.getSignCertificateChain();
                Calendar cal = pkcs7.getSignDate();
                List<VerificationException> errors = CertificateVerification.verifyCertificates(certs, ks, cal);
                if (errors.size() == 0) {
                    X509Certificate signCert = (X509Certificate) certs[0];
                    X509Certificate issuerCert = (certs.length > 1 ? (X509Certificate) certs[1] : null);
                    verified = checkSignatureRevocation(pkcs7, signCert, issuerCert, cal.getTime())
                            && checkSignatureRevocation(pkcs7, signCert, issuerCert, new Date());
                }
            }
        }
        reader.close();
    } catch (Exception e) {
        throw new SignatureException(e.getMessage(), e);
    }
    return verified;
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    Security.addProvider(new BouncyCastleProvider());

    PdfReader reader = new PdfReader(input.toString());
    AcroFields fields = reader.getAcroFields();
    ArrayList<String> names = fields.getSignatureNames();
    String result = "Passed";

    for (int i = 0; i < names.size(); i++) {
        String name = names.get(i);

        try {/*from  w  ww  .  j  a  v  a2  s. c o m*/
            PdfPKCS7 pk = fields.verifySignature(name);
            X509Certificate certificate = pk.getSigningCertificate();
            certificate.checkValidity();

            if (!SignatureUtils.isCertificateSelfSigned(certificate)) {

                Set<Certificate> trustedRootCerts = new HashSet<Certificate>();
                Set<Certificate> intermediateCerts = new HashSet<Certificate>();

                for (Certificate c : pk.getSignCertificateChain()) {
                    X509Certificate cert = (X509Certificate) c;
                    cert.checkValidity();

                    if (SignatureUtils.isCertificateSelfSigned(c))
                        trustedRootCerts.add(c);
                    else
                        intermediateCerts.add(c);
                }

                SignatureUtils.verifyCertificateChain(trustedRootCerts, intermediateCerts, certificate);
                if (pk.getCRLs() != null) {
                    for (CRL crl : pk.getCRLs()) {
                        if (crl.isRevoked(certificate)) {
                            result = "Signing certificate is included on a Certificate Revocation List";
                        }
                    }
                }
            }
        } catch (NoSuchFieldError e) {
            result = "Missing signature timestamp field";
        } catch (CertificateExpiredException e) {
            result = "Contains expired certificates";
        } catch (CertificateNotYetValidException e) {
            result = "Contains certificates not yet valid";
        }
    }

    reader.close();
    return result;
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

private static StringBuilder getExtractionInformation(AcroFields fields, ArrayList<?> names,
        Path outputContents, String filename) throws IOException {

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < names.size(); i++) {
        String name = (String) names.get(i);
        Item item = fields.getFieldItem(name);

        PdfDictionary widget = item.getWidget(0);
        PdfDictionary infoDictionary = widget.getAsDict(PdfName.V);
        sb.append("<signature>\n");

        try {/*  w w w  . ja v  a  2  s.c om*/
            PdfPKCS7 pk = fields.verifySignature(name);
            sb = addElementToExtractionResult(sb, "name", name);
            sb = addElementToExtractionResult(sb, "sign-name", pk.getSignName());
            sb = addElementToExtractionResult(sb, "version", Integer.toString(pk.getVersion()));
            sb = addElementToExtractionResult(sb, "reason", pk.getReason());
            sb = addElementToExtractionResult(sb, "location", pk.getLocation());

            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

            if (pk.getTimeStampDate() != null) {
                String timestamp = formatter.format(pk.getTimeStampDate().getTime());
                sb = addElementToExtractionResult(sb, "timestamp-time", timestamp);
            }

            if (pk.getSignDate() != null) {
                String sign = formatter.format(pk.getSignDate().getTime());
                sb = addElementToExtractionResult(sb, "sign-time", sign);
            }

            sb = addElementToExtractionResult(sb, "digest-algorithm", pk.getDigestAlgorithm());
            sb = addElementToExtractionResult(sb, "hash-algorithm", pk.getHashAlgorithm());
            sb = addElementToExtractionResult(sb, "covers-whole-document",
                    Boolean.toString(fields.signatureCoversWholeDocument(name)));
            sb = addElementToExtractionResult(sb, "ft", widget.get(PdfName.FT).toString());

            if (infoDictionary.contains(PdfName.CONTACTINFO))
                sb = addElementToExtractionResult(sb, "contact-info",
                        infoDictionary.getAsString(PdfName.CONTACTINFO).toString());

            if (infoDictionary.contains(PdfName.FILTER))
                sb = addElementToExtractionResult(sb, "filter", infoDictionary.get(PdfName.FILTER).toString());

            if (infoDictionary.contains(PdfName.SUBFILTER))
                sb = addElementToExtractionResult(sb, "subfilter",
                        infoDictionary.get(PdfName.SUBFILTER).toString());

            if (infoDictionary.contains(PdfName.LOCK))
                sb = addElementToExtractionResult(sb, "lock", "true");

            if (infoDictionary.contains(PdfName.CONTENTS)) {
                PdfString elementName = infoDictionary.getAsString(PdfName.CONTENTS);
                Files.write(outputContents, elementName.toUnicodeString().getBytes());
                sb = addElementToExtractionResult(sb, "contents", filename + ".pkcs7");
            }

        } catch (NoSuchFieldError e) {
            LOGGER.warn("DS information extraction did not execute properly");
        }

        sb.append("</signature>");
    }

    return sb;
}

From source file:org.roda.core.plugins.plugins.characterization.PDFSignatureUtils.java

public static String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    Security.addProvider(new BouncyCastleProvider());

    PdfReader reader = new PdfReader(input.toString());
    AcroFields fields = reader.getAcroFields();
    ArrayList<String> names = fields.getSignatureNames();
    String result = "Passed";

    for (int i = 0; i < names.size(); i++) {
        String name = names.get(i);

        try {//from   w w  w.  j a v  a  2s  . co  m
            PdfPKCS7 pk = fields.verifySignature(name);
            X509Certificate certificate = pk.getSigningCertificate();
            certificate.checkValidity();

            if (!SignatureUtils.isCertificateSelfSigned(certificate)) {

                Set<Certificate> trustedRootCerts = new HashSet<>();
                Set<Certificate> intermediateCerts = new HashSet<>();

                for (Certificate c : pk.getSignCertificateChain()) {
                    X509Certificate cert = (X509Certificate) c;
                    cert.checkValidity();

                    if (SignatureUtils.isCertificateSelfSigned(c))
                        trustedRootCerts.add(c);
                    else
                        intermediateCerts.add(c);
                }

                SignatureUtils.verifyCertificateChain(trustedRootCerts, intermediateCerts, certificate);
                if (pk.getCRLs() != null) {
                    for (CRL crl : pk.getCRLs()) {
                        if (crl.isRevoked(certificate)) {
                            result = "Signing certificate is included on a Certificate Revocation List";
                        }
                    }
                }
            }
        } catch (NoSuchFieldError e) {
            result = "Missing signature timestamp field";
        } catch (CertificateExpiredException e) {
            result = "Contains expired certificates";
        } catch (CertificateNotYetValidException e) {
            result = "Contains certificates not yet valid";
        }
    }

    reader.close();
    return result;
}