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

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

Introduction

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

Prototype

public ArrayList getSignatureNames() 

Source Link

Document

Gets the field names that have signatures and are signed.

Usage

From source file:androidGLUESigner.pdf.PDFSigExtractor.java

License:Open Source License

/**
 * extracts the signature field for previewing.
 * @throws IOException /*from   w  w w  .jav a2 s  . c  o m*/
 */
public static ArrayList<SignatureInfo> getSignatureInfo(String inputPath) {
    PdfReader reader;
    try {
        reader = new PdfReader(inputPath);
    } catch (IOException e) {
        return new ArrayList<SignatureInfo>();
    }
    AcroFields af = reader.getAcroFields();
    ArrayList names = af.getSignatureNames();
    ArrayList<SignatureInfo> signatures = new ArrayList<SignatureInfo>();
    // For every signature :
    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        SignatureInfo sigInfo = new SignatureInfo();
        // get coordinates
        float[] position = af.getFieldPositions(name);
        // page number
        float page = position[0];
        // left
        float llx = position[1];
        // bottom
        float lly = position[2];
        // right
        float urx = position[3];
        // top
        float ury = position[4];

        // get size of pdf page
        Rectangle size = reader.getPageSize((int) page);
        float height = size.getHeight();
        // subtract height to translate to Android canvas coordinate system
        lly = height - lly;
        ury = height - ury;
        float ulx = llx;

        // create a Rectangle from obtained signature field coordinates
        Rect sigRect = new Rect((int) ulx, (int) ury, (int) urx, (int) lly);
        sigInfo.setGraphicRect(sigRect, 1.0f);
        // obtain additional information like reason, location, ...
        PdfDictionary sig = af.getSignatureDictionary(name);
        sigInfo.setSignatureName(sig.getAsString(PdfName.NAME).toString());
        sigInfo.setSignatureLocation(sig.getAsString(PdfName.LOCATION).toString());
        sigInfo.setSignatureReason(sig.getAsString(PdfName.REASON).toString());
        sigInfo.setSignatureType(SignatureType.NORMAL);
        sigInfo.setPageNumber((int) page);
        // add new signature information to signatures
        signatures.add(sigInfo);
    }
    return signatures;
}

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

License:Open Source License

public List<String> verificar(String direccionPDF) throws SignatureVerificationException {
    try {//  w  ww  .  j  a  v  a  2  s. c  o  m
        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:es.gob.afirma.signers.pades.AOPDFSigner.java

License:Open Source License

/** Recupera el &aacute;rbol de nodos de firma de una firma electr&oacute;nica.
 * Los nodos del &aacute;rbol ser&aacute;n textos con el <i>CommonName</i> (CN X.500)
 * del titular del certificado u objetos de tipo AOSimpleSignInfo con la
 * informaci&oacute;n b&aacute;sica de las firmas individuales, seg&uacute;n
 * el valor del par&aacute;metro <code>asSimpleSignInfo</code>. Los nodos se
 * mostrar&aacute;n en el mismo orden y con la misma estructura con el que
 * aparecen en la firma electr&oacute;nica.<br>
 * La propia estructura de firma se considera el nodo ra&iacute;z, la firma y cofirmas
 * pender&aacute;n directamentede de este.
 * @param sign Firma electr&oacute;nica de la que se desea obtener la estructura.
 * @param asSimpleSignInfo//  w ww.  j a  v a2  s . c  o  m
 *        Si es <code>true</code> se devuelve un &aacute;rbol con la
 *        informaci&oacute;n b&aacute;sica de cada firma individual
 *        mediante objetos <code>AOSimpleSignInfo</code>, si es <code>false</code> un &aacute;rbol con los nombres (CN X.500) de los
 *        titulares certificados.
 * @return &Aacute;rbol de nodos de firma o <code>null</code> en caso de error. */
@Override
public AOTreeModel getSignersStructure(final byte[] sign, final boolean asSimpleSignInfo) {

    final AOTreeNode root = new AOTreeNode("Datos"); //$NON-NLS-1$

    if (!isPdfFile(sign)) {
        return new AOTreeModel(root);
    }

    PdfReader pdfReader;
    try {
        pdfReader = new PdfReader(sign);
    } catch (final BadPasswordException e) {
        try {
            pdfReader = new PdfReader(sign,
                    new String(AOUIFactory.getPassword(CommonPdfMessages.getString("AOPDFSigner.0"), //$NON-NLS-1$
                            null)).getBytes());
        } catch (final BadPasswordException e2) {
            LOGGER.severe("La contrasena del PDF no es valida, se devolvera un arbol vacio: " + e2); //$NON-NLS-1$
            return new AOTreeModel(root);
        } catch (final Exception e3) {
            LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e3); //$NON-NLS-1$
            return new AOTreeModel(root);
        }
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido leer el PDF, se devolvera un arbol vacio: " + e); //$NON-NLS-1$
        return new AOTreeModel(root);
    }

    final AcroFields af;
    try {
        af = pdfReader.getAcroFields();
    } catch (final Exception e) {
        LOGGER.severe(
                "No se ha podido obtener la informacion de los firmantes del PDF, se devolvera un arbol vacio: " //$NON-NLS-1$
                        + e);
        return new AOTreeModel(root);
    }

    final List<String> names = af.getSignatureNames();
    Object pkcs1Object = null;
    for (int i = 0; i < names.size(); ++i) {
        final PdfPKCS7 pcks7;
        try {
            pcks7 = af.verifySignature(names.get(i).toString());
        } catch (final Exception e) {
            LOGGER.severe("El PDF contiene una firma corrupta o con un formato desconocido (" + //$NON-NLS-1$
                    names.get(i).toString() + "), se continua con las siguientes si las hubiese: " + e //$NON-NLS-1$
            );
            continue;
        }
        if (asSimpleSignInfo) {
            final AOSimpleSignInfo ssi = new AOSimpleSignInfo(
                    new X509Certificate[] { pcks7.getSigningCertificate() }, pcks7.getSignDate().getTime());

            // Extraemos el PKCS1 de la firma
            try {
                // iText antiguo
                final Field digestField = Class.forName("com.lowagie.text.pdf.PdfPKCS7") //$NON-NLS-1$
                        .getDeclaredField("digest"); //$NON-NLS-1$
                digestField.setAccessible(true);
                pkcs1Object = digestField.get(pcks7);
            } catch (final Exception e) {
                LOGGER.severe(
                        "No se ha podido obtener informacion de una de las firmas del PDF, se continuara con la siguiente: " //$NON-NLS-1$
                                + e);
                continue;
            }
            if (pkcs1Object instanceof byte[]) {
                ssi.setPkcs1((byte[]) pkcs1Object);
            }
            root.add(new AOTreeNode(ssi));
        } else {
            root.add(new AOTreeNode(AOUtil.getCN(pcks7.getSigningCertificate())));
        }
    }

    return new AOTreeModel(root);
}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*//from w ww  .j  ava2s  .  c  o m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

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

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want the multiple signatures, the
             * signatures are appended sequentially to the end of the document. The recursive call helps to get the
             * signature from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFSignatureService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDict outerCatalog, SignatureValidationCallback callback,
        List<String> alreadyLoadedRevisions) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*//from   ww  w  .  j  a  v  a 2  s. c o m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

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

            PdfDict signatureDictionary = new ITextPdfDict(af.getSignatureDictionary(name));
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(new ITextPdfDict(reader.getCatalog()), outerCatalog,
                        pk.getSigningCertificate(), cal != null ? cal.getTime() : null, pkc,
                        signatureDictionary, new ITextPdfSignatureInfo(pk));
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDict catalog = new ITextPdfDict(reader.getCatalog());

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures are
             * appended sequentially to the end of the document. The recursive call help to get the signature from the
             * original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings("unchecked")
private void validateSignatures(InputStream input, PdfDictionary outerCatalog,
        SignatureValidationCallback callback, List<String> alreadyLoadedRevisions)
        throws IOException, SignatureException {

    PdfReader reader = new PdfReader(input);
    AcroFields af = reader.getAcroFields();

    /*//from w w  w .  jav  a2 s . co  m
     * Search the whole document of a signature
     */
    ArrayList<String> names = af.getSignatureNames();

    LOG.info(names.size() + " signature(s)");
    // For every signature :
    for (String name : names) {

        // Affichage du nom
        LOG.info("Signature name: " + name);
        LOG.info("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        // Affichage sur les revision - version
        LOG.info("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        /*
         * We are only interrested in the validation of signature that covers the whole document.
         */
        if (af.signatureCoversWholeDocument(name)) {

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

            PdfDictionary signatureDictionary = af.getSignatureDictionary(name);
            String revisionName = Integer.toString(af.getRevision(name));
            if (!alreadyLoadedRevisions.contains(revisionName)) {
                callback.validate(reader, outerCatalog, pk.getSigningCertificate(),
                        cal != null ? cal.getTime() : null, pkc, signatureDictionary, pk);
                alreadyLoadedRevisions.add(revisionName);
            }

        } else {

            PdfDictionary catalog = reader.getCatalog();

            /*
             * We open the version of the document that was protected by the signature
             */
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream ip = af.extractRevision(name);
            IOUtils.copy(ip, out);
            out.close();
            ip.close();

            /*
             * You can sign a PDF document with only one signature. So when we want multiple signature, signatures
             * are appended sequentially to the end of the document. The recursive call help to get the signature
             * from the original document.
             */
            validateSignatures(new ByteArrayInputStream(out.toByteArray()), catalog, callback,
                    alreadyLoadedRevisions);

        }
    }

}

From source file:net.sf.jsignpdf.SignerLogic.java

License:Mozilla Public License

/**
 * Signs a single file./*from  w  w  w. j  a  va  2 s  . c  om*/
 * 
 * @return true when signing is finished succesfully, false otherwise
 */
public boolean signFile() {
    final String outFile = options.getOutFileX();
    if (!validateInOutFiles(options.getInFile(), outFile)) {
        LOGGER.info(RES.get("console.skippingSigning"));
        return false;
    }

    boolean finished = false;
    Throwable tmpException = null;
    FileOutputStream fout = null;
    try {
        SSLInitializer.init(options);

        final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options);
        final PrivateKey key = pkInfo.getKey();
        final Certificate[] chain = pkInfo.getChain();
        if (ArrayUtils.isEmpty(chain)) {
            // the certificate was not found
            LOGGER.info(RES.get("console.certificateChainEmpty"));
            return false;
        }
        LOGGER.info(RES.get("console.createPdfReader", options.getInFile()));
        PdfReader reader;
        try {
            reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
        } catch (Exception e) {
            try {
                reader = new PdfReader(options.getInFile(), new byte[0]);
            } catch (Exception e2) {
                // try to read without password
                reader = new PdfReader(options.getInFile());
            }
        }

        LOGGER.info(RES.get("console.createOutPdf", outFile));
        fout = new FileOutputStream(outFile);

        final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX();

        LOGGER.info(RES.get("console.createSignature"));
        char tmpPdfVersion = '\0'; // default version - the same as input
        if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) {
            // this covers also problems with visible signatures (embedded
            // fonts) in PDF 1.2, because the minimal version
            // for hash algorithms is 1.3 (for SHA1)
            if (options.isAppendX()) {
                // if we are in append mode and version should be updated
                // then return false (not possible)
                LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode"));
                return false;
            }
            tmpPdfVersion = hashAlgorithm.getPdfVersion();
            LOGGER.info(RES.get("console.updateVersion",
                    new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }));
        }

        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null,
                options.isAppendX());
        if (!options.isAppendX()) {
            // we are not in append mode, let's remove existing signatures
            // (otherwise we're getting to troubles)
            final AcroFields acroFields = stp.getAcroFields();
            @SuppressWarnings("unchecked")
            final List<String> sigNames = acroFields.getSignatureNames();
            for (String sigName : sigNames) {
                acroFields.removeField(sigName);
            }
        }
        if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) {
            LOGGER.info(RES.get("console.setEncryption"));
            final int tmpRight = options.getRightPrinting().getRight()
                    | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0)
                    | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0)
                    | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0)
                    | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0)
                    | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0)
                    | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0);
            switch (options.getPdfEncryption()) {
            case PASSWORD:
                stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight);
                break;
            case CERTIFICATE:
                final X509Certificate encCert = KeyStoreUtils
                        .loadCertificate(options.getPdfEncryptionCertFile());
                if (encCert == null) {
                    LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile",
                            StringUtils.defaultString(options.getPdfEncryptionCertFile())));
                    return false;
                }
                if (!KeyStoreUtils.isEncryptionSupported(encCert)) {
                    LOGGER.error(RES.get("console.pdfEncError.cantUseCertificate",
                            encCert.getSubjectDN().getName()));
                    return false;
                }
                stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight },
                        PdfWriter.ENCRYPTION_AES_128);
                break;
            default:
                LOGGER.error(RES.get("console.unsupportedEncryptionType"));
                return false;
            }
        }

        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        final String reason = options.getReason();
        if (StringUtils.isNotEmpty(reason)) {
            LOGGER.info(RES.get("console.setReason", reason));
            sap.setReason(reason);
        }
        final String location = options.getLocation();
        if (StringUtils.isNotEmpty(location)) {
            LOGGER.info(RES.get("console.setLocation", location));
            sap.setLocation(location);
        }
        final String contact = options.getContact();
        if (StringUtils.isNotEmpty(contact)) {
            LOGGER.info(RES.get("console.setContact", contact));
            sap.setContact(contact);
        }
        LOGGER.info(RES.get("console.setCertificationLevel"));
        sap.setCertificationLevel(options.getCertLevelX().getLevel());

        if (options.isVisible()) {
            // visible signature is enabled
            LOGGER.info(RES.get("console.configureVisible"));
            LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers())));
            sap.setAcro6Layers(options.isAcro6Layers());

            final String tmpImgPath = options.getImgPath();
            if (tmpImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpImgPath));
                final Image img = Image.getInstance(tmpImgPath);
                LOGGER.info(RES.get("console.setSignatureGraphic"));
                sap.setSignatureGraphic(img);
            }
            final String tmpBgImgPath = options.getBgImgPath();
            if (tmpBgImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpBgImgPath));
                final Image img = Image.getInstance(tmpBgImgPath);
                LOGGER.info(RES.get("console.setImage"));
                sap.setImage(img);
            }
            LOGGER.info(RES.get("console.setImageScale"));
            sap.setImageScale(options.getBgImgScale());
            LOGGER.info(RES.get("console.setL2Text"));
            final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN");
            final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z")
                    .format(sap.getSignDate().getTime());
            if (options.getL2Text() != null) {
                final Map<String, String> replacements = new HashMap<String, String>();
                replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer));
                replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp);
                replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location));
                replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason));
                replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact));
                final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements);
                sap.setLayer2Text(l2text);
            } else {
                final StringBuilder buf = new StringBuilder();
                buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n');
                buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp);
                if (StringUtils.isNotEmpty(reason))
                    buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason);
                if (StringUtils.isNotEmpty(location))
                    buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location);
                sap.setLayer2Text(buf.toString());
            }
            if (FontUtils.getL2BaseFont() != null) {
                sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize()));
            }
            LOGGER.info(RES.get("console.setL4Text"));
            sap.setLayer4Text(options.getL4Text());
            LOGGER.info(RES.get("console.setRender"));
            RenderMode renderMode = options.getRenderMode();
            if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) {
                LOGGER.warn(
                        "Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY.");
                LOGGER.info(RES.get("console.renderModeFallback"));
                renderMode = RenderMode.DESCRIPTION_ONLY;
            }
            sap.setRender(renderMode.getRender());
            LOGGER.info(RES.get("console.setVisibleSignature"));
            int page = options.getPage();
            if (page < 1 || page > reader.getNumberOfPages()) {
                page = reader.getNumberOfPages();
            }
            sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(),
                    options.getPositionURX(), options.getPositionURY()), page, null);
        }

        LOGGER.info(RES.get("console.processing"));
        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        if (!StringUtils.isEmpty(reason)) {
            dic.setReason(sap.getReason());
        }
        if (!StringUtils.isEmpty(location)) {
            dic.setLocation(sap.getLocation());
        }
        if (!StringUtils.isEmpty(contact)) {
            dic.setContact(sap.getContact());
        }
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);

        final Proxy tmpProxy = options.createProxy();

        final CRLInfo crlInfo = new CRLInfo(options, chain);

        // CRLs are stored twice in PDF c.f.
        // PdfPKCS7.getAuthenticatedAttributeBytes
        final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount());
        final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null,
                false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName());
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();
        byte[] ocsp = null;
        if (options.isOcspEnabledX() && chain.length >= 2) {
            LOGGER.info(RES.get("console.getOCSPURL"));
            String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
            if (StringUtils.isEmpty(url)) {
                // get from options
                LOGGER.info(RES.get("console.noOCSPURL"));
                url = options.getOcspServerUrl();
            }
            if (!StringUtils.isEmpty(url)) {
                LOGGER.info(RES.get("console.readingOCSP", url));
                final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0],
                        (X509Certificate) chain[1], url);
                ocspClient.setProxy(tmpProxy);
                ocsp = ocspClient.getEncoded();
            }
        }
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
        sgn.update(sh, 0, sh.length);

        TSAClientBouncyCastle tsc = null;
        if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) {
            LOGGER.info(RES.get("console.creatingTsaClient"));
            if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl(),
                        StringUtils.defaultString(options.getTsaUser()),
                        StringUtils.defaultString(options.getTsaPasswd()));
            } else {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl());

            }
            final String tsaHashAlg = options.getTsaHashAlgWithFallback();
            LOGGER.info(RES.get("console.settingTsaHashAlg", tsaHashAlg));
            tsc.setHashAlgorithm(tsaHashAlg);
            tsc.setProxy(tmpProxy);
            final String policyOid = options.getTsaPolicy();
            if (StringUtils.isNotEmpty(policyOid)) {
                LOGGER.info(RES.get("console.settingTsaPolicy", policyOid));
                tsc.setPolicy(policyOid);
            }
        }
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

        if (contentEstimated + 2 < encodedSig.length) {
            System.err.println(
                    "SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length);
            throw new Exception("Not enough space");
        }

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        LOGGER.info(RES.get("console.closeStream"));
        sap.close(dic2);
        fout.close();
        fout = null;
        finished = true;
    } catch (Exception e) {
        LOGGER.error(RES.get("console.exception"), e);
    } catch (OutOfMemoryError e) {
        LOGGER.fatal(RES.get("console.memoryError"), e);
    } finally {
        if (fout != null) {
            try {
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error")));
        options.fireSignerFinishedEvent(tmpException);
    }
    return finished;
}

From source file:net.sf.jsignpdf.verify.VerifierLogic.java

License:Mozilla Public License

/**
 * Verifies signature(s) in PDF document.
 * // w w w . j  a v a2 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:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

License:Open Source License

protected List<X509Certificate> getCertificates(PdfReader pdfReader) throws SignException {
    List<X509Certificate> pdfCertificates = new ArrayList<X509Certificate>();
    AcroFields acroFields = pdfReader.getAcroFields();
    @SuppressWarnings("unchecked")
    List<String> signatureNames = acroFields.getSignatureNames();
    for (String signatureName : signatureNames) {
        PdfPKCS7 pdfPKCS7 = acroFields.verifySignature(signatureName);
        X509Certificate signingCertificate = pdfPKCS7.getSigningCertificate();
        pdfCertificates.add(signingCertificate);
    }//from   w ww  . j av  a  2 s .co m
    return pdfCertificates;
}

From source file:org.opensignature.opensignpdf.tools.Pkcs7Extractor.java

License:Open Source License

/**
 * @param args/*  w  ww .  ja v  a 2 s.co  m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
        if (args.length < 1) {
            System.out.println("Usage: EstraiPkcs7 <pdf file relative to current dir>");
            System.exit(1);
        }
        String filename = args[0];

        PdfReader reader = new PdfReader(filename);
        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("Signature name: " + name);
            System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
            System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
            // Start revision extraction
            // FileOutputStream out = new FileOutputStream("revision_" +
            // 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();
            // End revision extraction

            // PdfPKCS7 pk = af.verifySignature(name);

            PdfDictionary v = af.getSignatureDictionary(name);

            PdfString contents = (PdfString) PdfReader.getPdfObject(v.get(PdfName.CONTENTS));

            // Start pkcs7 extraction
            FileOutputStream fos = new FileOutputStream(filename + "_signeddata_" + name + ".pk7");
            System.out.println(k + ") Estrazione pkcs7: " + filename + "_signeddata_" + name + ".pk7");
            fos.write(contents.getOriginalBytes());
            fos.flush();
            fos.close();
            // End pkcs7 extraction

            /* Commentato per evitare dipendenze da BC
            Security.insertProviderAt(new BouncyCastleProvider(), 3);
                    
            // nota: dipendenza da provider BC per "SHA1withRSA"
            PdfPKCS7 pk = new PdfPKCS7(contents.getOriginalBytes(), "BC");
                    
                    
                    
            Calendar cal = pk.getSignDate();
            Certificate pkc[] = pk.getCertificates();
            System.out.println("Got " + pkc.length
                + " certificates from pdf");
            System.out
                .println("Subject of signer: "
                        + PdfPKCS7.getSubjectFields(pk
                                .getSigningCertificate()));
            // System.out.println("Document modified: " + !pk.verify());
            // Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null,
            // cal);
            // if (fails == null)
            // System.out.println("Certificates verified against the
            // KeyStore");
            // else
            // System.out.println("Certificate failed: " + fails[1]);
                     
            */
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

    /* decommentare se si riabilita la parte relativa a PdfPKCS7 nel main
            
    catch (InvalidKeyException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CRLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (CertificateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchProviderException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    */

}