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

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

Introduction

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

Prototype

public ArrayList<String> getSignatureNames() 

Source Link

Document

Gets the field names that have signatures and are signed.

Usage

From source file:com.swisscom.ais.itext.PDF.java

License:Open Source License

/**
 * Add signature information (reason for signing, location, contact, date) and create hash from pdf document
 *
 * @param signDate        Date of signing
 * @param estimatedSize   The estimated size for signatures
 * @param hashAlgorithm   The hash algorithm which will be used to sign the pdf
 * @param isTimestampOnly If it is a timestamp signature. This is necessary because the filter is an other one compared to a "standard" signature
 * @return Hash of pdf as bytes/*from  w w w. j  a va2s .  c  om*/
 * @throws Exception 
 */
public byte[] getPdfHash(@Nonnull Calendar signDate, int estimatedSize, @Nonnull String hashAlgorithm,
        boolean isTimestampOnly) throws Exception {

    pdfReader = new PdfReader(inputFilePath, pdfPassword != null ? pdfPassword.getBytes() : null);
    AcroFields acroFields = pdfReader.getAcroFields();
    boolean hasSignature = acroFields.getSignatureNames().size() > 0;
    byteArrayOutputStream = new ByteArrayOutputStream();
    pdfStamper = PdfStamper.createSignature(pdfReader, byteArrayOutputStream, '\0', null, hasSignature);
    pdfStamper.setXmpMetadata(pdfReader.getMetadata());

    pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
    pdfSignature = new PdfSignature(PdfName.ADOBE_PPKLITE,
            isTimestampOnly ? PdfName.ETSI_RFC3161 : PdfName.ADBE_PKCS7_DETACHED);
    pdfSignature.setReason(signReason);
    pdfSignature.setLocation(signLocation);
    pdfSignature.setContact(signContact);
    pdfSignature.setDate(new PdfDate(signDate));
    pdfSignatureAppearance.setCryptoDictionary(pdfSignature);

    // certify the pdf, if requested
    if (certificationLevel > 0) {
        // check: at most one certification per pdf is allowed
        if (pdfReader.getCertificationLevel() != PdfSignatureAppearance.NOT_CERTIFIED)
            throw new Exception(
                    "Could not apply -certlevel option. At most one certification per pdf is allowed, but source pdf contained already a certification.");
        pdfSignatureAppearance.setCertificationLevel(certificationLevel);
    }

    HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));

    pdfSignatureAppearance.preClose(exc);

    MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm);
    InputStream rangeStream = pdfSignatureAppearance.getRangeStream();
    int i;
    while ((i = rangeStream.read()) != -1) {
        messageDigest.update((byte) i);
    }

    return messageDigest.digest();
}

From source file:controller.CCInstance.java

License:Open Source License

public final ArrayList<SignatureValidation> validatePDF(final String file, final ValidationListener vl)
        throws IOException, DocumentException, GeneralSecurityException {
    this.validating = true;

    final PdfReader reader = new PdfReader(file);
    final AcroFields af = reader.getAcroFields();
    final ArrayList names = af.getSignatureNames();
    final ArrayList<SignatureValidation> validateList = new ArrayList<>();
    X509Certificate x509c = null;

    Security.setProperty("ocsp.enable", "true");
    System.setProperty("com.sun.security.enableCRLDP", "true");

    boolean nextValid = true;

    for (Object o : names) {
        if (!validating) {
            return null;
        }/*from  ww w .j  a v a 2s.c  om*/

        final String name = (String) o;
        final PdfPKCS7 pk = af.verifySignature(name, "BC");
        final Certificate pkc[] = pk.getCertificates();
        x509c = (X509Certificate) pkc[pkc.length - 1];

        final Certificate[] aL = pkc;//getCompleteCertificateChain(x509c);

        if (null == aL || 0 == aL.length) {
            return null;
        }

        CertificateStatus ocspCertificateStatus = CertificateStatus.UNCHECKED;

        BasicOCSPResp ocspResp = pk.getOcsp();
        if (null != ocspResp && pk.isRevocationValid()) {
            for (SingleResp singleResp : ocspResp.getResponses()) {
                if (null == singleResp.getCertStatus()) {
                    ocspCertificateStatus = CertificateStatus.OK;
                } else if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    if (ocspResp.getProducedAt()
                            .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        ocspCertificateStatus = CertificateStatus.OK;
                    } else {
                        ocspCertificateStatus = CertificateStatus.REVOKED;
                    }
                } else if (singleResp.getCertStatus() instanceof UnknownStatus) {
                    ocspCertificateStatus = CertificateStatus.UNKNOWN;
                }
            }
        }

        CertificateStatus crlCertificateStatus = CertificateStatus.UNCHECKED;
        Collection<CRL> crlResp = pk.getCRLs();
        if (null != crlResp) {
            boolean revoked = false;
            for (CRL crl : crlResp) {
                if (crl.isRevoked(x509c)) {
                    revoked = true;
                }
            }
            crlCertificateStatus = revoked ? CertificateStatus.REVOKED : CertificateStatus.OK;
        }

        if (ocspCertificateStatus.equals(CertificateStatus.UNCHECKED)
                && crlCertificateStatus.equals(CertificateStatus.UNCHECKED)) {
            if (pkc.length == 1) {
                Certificate[] completeChain = getCompleteTrustedCertificateChain(x509c);
                if (completeChain.length == 1) {
                    ocspCertificateStatus = CertificateStatus.UNCHAINED;
                } else {
                    ocspCertificateStatus = CertificateStatus.CHAINED_LOCALLY;
                }
            }
        }

        final TimeStampToken tst = pk.getTimeStampToken();
        boolean validTimestamp = false;
        if (null != tst) {
            final boolean hasTimestamp = pk.verifyTimestampImprint();
            validTimestamp = hasTimestamp && CertificateVerification.verifyTimestampCertificates(tst, ks, null);
        }

        PdfDictionary pdfDic = reader.getAcroFields().getSignatureDictionary(name);
        SignaturePermissions sp = new SignaturePermissions(pdfDic, null);

        boolean isValid;
        if (nextValid) {
            isValid = pk.verify();
        } else {
            isValid = false;
        }

        List<AcroFields.FieldPosition> posList = af.getFieldPositions(name);
        final SignatureValidation signature = new SignatureValidation(file, name, pk, !pk.verify(),
                af.signatureCoversWholeDocument(name), af.getRevision(name), af.getTotalRevisions(),
                reader.getCertificationLevel(), ocspCertificateStatus, crlCertificateStatus, validTimestamp,
                posList, sp, isValid);
        validateList.add(signature);

        if (null != vl) {
            vl.onValidationComplete(signature);
        }
        if (!sp.isFillInAllowed()) {
            nextValid = false;
        }
    }
    return validateList;
}

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

License:Open Source License

private SignatureDisplay display(AcroFields fields) {
    SignatureDisplay result = new SignatureDisplay();

    // digitalsignatures20130304.pdf : Code sample 5.1
    ArrayList<String> names = fields.getSignatureNames();

    // Print number of signatures
    to.println(String.format("Number of signatures: %d", names.size()));
    to.println(String.format("Number of document revisions: %d", fields.getTotalRevisions()));
    result.nRevisions = fields.getTotalRevisions();

    List<Signature> signatures = new ArrayList<>();

    for (String name : names) {
        to.println(String.format("Signature field name: %s", name));

        to.indentMore();//from  w w w.j  av  a2 s. co  m
        Signature signature;
        try {
            signature = display(fields, name); // May throw OperationException
        } finally {
            to.indentLess();
        }
        signature.id = name;
        signatures.add(signature);
    }

    result.signatures = signatures;

    return result;
}

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;//from  w  w  w  .j a v a2 s .  co m
    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?//from w ww . j a va 2  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:ec.rubrica.pdf.PDFUtils.java

License:Open Source License

public static boolean yaEstaFirmado(byte[] archivoPDF) {
    try {//from  w  w  w  .j  a  v a2s.com
        // Verificar si ya esta firmado?
        PdfReader reader = new PdfReader(archivoPDF);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> nombreLista = fields.getSignatureNames();
        for (String nombre : nombreLista) {
            System.out.println("Firmante=" + nombre);
        }
        return (nombreLista.size() == 1);
    } catch (IOException e) {
        throw new RuntimeException(e); // FIXME
    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*from   w w  w . ja v  a2 s  . c  o  m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    NodeService ns = serviceRegistry.getNodeService();
    if (ns.exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);

    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the box
    box = (JSONObject) positionObj.get("box");

    try {
        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = new PdfStamper(reader, cos);

        // does a field with this name already exist?
        AcroFields allFields = stamp.getAcroFields();

        // if this doc is already signed, cannot add a new sig field without 
        if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) {
            throw new AlfrescoRuntimeException("This document has signatures applied, "
                    + "adding a new signature field would invalidate existing signatures");
        }

        // cant create duplicate field names
        if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) {
            throw new AlfrescoRuntimeException(
                    "A signature field named " + fieldName + " already exists in this document");
        }

        // create the signature field
        Rectangle pageRect = reader.getPageSizeWithRotation(page);
        Rectangle sigRect = positionBlock(pageRect, box);
        PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(),
                sigRect.getRight(), sigRect.getTop());

        // style the field (no borders)
        sigField.setBorder(new PdfBorderArray(0, 0, 0));
        sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID));
        allFields.regenerateField(fieldName);

        // apply the change and close streams
        stamp.close();
        reader.close();
        cos.close();

        // once the signature field has been added, apply the sig field aspect
        if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) {
            ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null);
        }

        // now update the signature fields metadata
        Serializable currentFields = ns.getProperty(actionedUponNodeRef,
                CounterSignSignatureModel.PROP_SIGNATUREFIELDS);
        ArrayList<String> fields = new ArrayList<String>();

        if (currentFields != null) {
            fields.addAll((List<String>) currentFields);
        }

        fields.add(fieldName);
        ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields);
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (DocumentException dex) {
        throw new AlfrescoRuntimeException(dex.getMessage());
    }
}

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  ww  w.ja v a 2 s.co m*/
        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)//from  w w  w . j  av 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 ww. j  a  v a2s  .  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;
}