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

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

Introduction

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

Prototype

public X509Certificate getSigningCertificate() 

Source Link

Document

Get the X.509 certificate actually used to sign the digest.

Usage

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

License:Open Source License

/**
 * TODO: Mas de dos firmas?//from   ww  w  . ja v  a2s .  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 {// www.j a va 2  s  . co m
            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/*w  w  w  . j  a  v  a  2  s  .  c  o 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.opencps.pki.Pksc7SignatureContainer.java

License:Open Source License

/**
 * Produces the container with the signature.
 * @param data the data to sign//from  w w w . j a  v a2 s.  c  om
 * @return a container with the signature and other objects, like CRL and OCSP. The container will generally be a PKCS7 one.
 * @throws GeneralSecurityException 
 */
@Override
public byte[] sign(InputStream is) throws GeneralSecurityException {
    X509Certificate cert = signer.getCertificate();
    PdfPKCS7 sgn = new PdfPKCS7(encodedPkcs7, PdfName.ADBE_PKCS7_DETACHED, null);
    X509Certificate signingCert = sgn.getSigningCertificate();

    if (!signingCert.getSerialNumber().equals(cert.getSerialNumber())) {
        throw new SignatureException(
                "Encoded pkcs7 is invalid. The certificate from signer not equal pkcs7's certificate");
    }

    return encodedPkcs7;
}

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   ww w.  j a  v a2 s. co  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.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 {/* w ww  . jav  a  2  s . c  o 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;
}