Example usage for com.itextpdf.text.pdf.security PdfPKCS7 getTimeStampDate

List of usage examples for com.itextpdf.text.pdf.security PdfPKCS7 getTimeStampDate

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf.security PdfPKCS7 getTimeStampDate.

Prototype

public Calendar getTimeStampDate() 

Source Link

Document

Gets the timestamp date

Usage

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

License:Open Source License

/**
 * TODO: Mas de dos firmas?//w  w w  . j a  va 2  s  .co 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:ec.rubrica.pdf.VerificadorFirmaPdf.java

License:Open Source License

public Verificacion verificar() throws OcspValidationException, SignatureException {
    int totalRevisiones = af.getTotalRevisions();
    Verificacion verificacion = new Verificacion(totalRevisiones);

    ArrayList<String> nombres = af.getSignatureNames();
    System.out.println("Cuantos nombres=" + nombres.size());

    for (String nombre1 : nombres) {
        System.out.println("nombre=" + nombre1);
        PdfPKCS7 pk = af.verifySignature(nombre1);
        X509Certificate certificadoFirmante = pk.getSigningCertificate();
        log.info("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
        Certificate[] chain = pk.getSignCertificateChain();

        // Verificar OCSP:
        try {//from   w ww . j  a v  a2s  .  c om
            verificarOscp(certificadoFirmante);
        } catch (OcspTimeoutException e) {
            throw new SignatureException(e);
        }
    }

    for (String nombre : nombres) {
        PdfPKCS7 pk = af.verifySignature(nombre);

        boolean firmaCubreTodoDocumento = af.signatureCoversWholeDocument(nombre);

        int revision = af.getRevision(nombre);

        X509Certificate certificadoFirmante = pk.getSigningCertificate();
        log.info("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));

        Calendar fechaFirma = pk.getSignDate();
        TimeStampToken tst = pk.getTimeStampToken();

        if (tst != null) {
            log.fine("La firma Tiene Time Stamp");
            fechaFirma = pk.getTimeStampDate();
        }

        boolean selladoTiempoCorrecto = false;

        if (!pk.isTsp() && tst != null) {
            try {
                selladoTiempoCorrecto = pk.verifyTimestampImprint();
            } catch (NoSuchAlgorithmException e) {
                throw new SignatureException(e);
            }
        }

        Certificate[] certificados = pk.getCertificates();

        // TODO: DEBUG
        Certificate[] chain = pk.getSignCertificateChain();
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = (X509Certificate) chain[i];
            System.out.println(String.format("[%s] %s", i, cert.getSubjectDN()));
            System.out.println(CertificateUtil.getOCSPURL(cert));
        }
        // TODO: DEBUG

        boolean documentoModificado = !pk.verify();

        Firma firma = new Firma(nombre, firmaCubreTodoDocumento, revision, certificadoFirmante, fechaFirma,
                selladoTiempoCorrecto, certificados, documentoModificado);

        // TODO: Implementar CRLs
        Collection<CRL> crls = null;

        Object error[] = CertificateVerification.verifyCertificates(certificados, cacerts, crls, fechaFirma);

        // TODO: Quitar el mensaje y usar una Enum
        if (error != null) {
            Object objetoConFalla = error[0];
            String mensaje = (String) error[1];

            Falla falla;

            if (objetoConFalla != null) {
                Certificate certConFalla = (Certificate) objetoConFalla;
                falla = new Falla(certConFalla, mensaje);
            } else {
                falla = new Falla(mensaje);
            }

            firma.setFalla(falla);
        }

        verificacion.addFirma(firma);
    }

    return verificacion;
}

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

License:Open Source License

/**
 * Constructor/*from w w w  .  java  2 s.co  m*/
 */
public PdfSignatureInfo(PdfPKCS7 pkcs7) {
    super(pkcs7.getSigningCertificate(), new CertificateInfo(pkcs7.getSigningCertificate()),
            pkcs7.getSignDate(), pkcs7.getTimeStampDate(), pkcs7.getDigestAlgorithm(),
            pkcs7.getHashAlgorithm());
    this.pkcs7 = pkcs7;
}

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 {//from  w ww.j  ava  2  s.c o  m
            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

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  ww.j  a  va 2s.c  o  m*/
            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;
}