Example usage for com.lowagie.text.pdf PdfName PdfName

List of usage examples for com.lowagie.text.pdf PdfName PdfName

Introduction

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

Prototype

public PdfName(byte bytes[]) 

Source Link

Document

Constructs a PdfName.

Usage

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void main(String[] args) throws Exception {
    byte[] pdf;//w ww.  java  2  s.  c  o m
    {
        File f = new File("c:/trabalhos/java/teste.pdf");
        FileInputStream fin = new FileInputStream(f);
        pdf = new byte[(int) f.length()];
        fin.read(pdf);
        fin.close();
    }

    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 256000;

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.setSignDate(Calendar.getInstance());
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    byte[] signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception {
    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 128000;

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);//from  w w w  .  j a  v  a  2  s.c  o  m
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static byte[] getHasheableRangeFromPDF(byte[] pdf) throws Exception {
    PdfReader reader = new PdfReader(pdf);
    OutputStream fout = new NullOutputStream();

    final int SIZE = 128000;

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);/*from   w  w  w  . java2s  .  c  om*/
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());

    byte[] outc = new byte[(SIZE - 2) / 2];
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
    System.out.println("Hash: " + MessageDigest.getInstance("MD5").digest(data, 0, data.length));
    return data;
}

From source file:com.aripd.clms.service.ContractServiceBean.java

@Override
public void generatePdf(ContractEntity contract) {
    String baseFontUrl = "/fonts/Quivira.otf";
    FontFactory.register(baseFontUrl);/*from  w  ww.  j  av  a 2s.c  o  m*/

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font18n = new Font(bf, 18, Font.NORMAL);
        Font font12n = new Font(bf, 12, Font.NORMAL);
        Font font8n = new Font(bf, 8, Font.NORMAL);
        Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE);
        Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY);
        Font font6n = new Font(bf, 6, Font.NORMAL);

        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        addMetaData(document);
        addTitlePage(document, contract);
        Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, });
        imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10);
        imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight());
        PdfImage stream = new PdfImage(imgBlue, "", null);
        stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
        PdfIndirectObject ref = writer.addToBody(stream);
        imgBlue.setDirectReference(ref.getIndirectReference());
        document.add(imgBlue);

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);

        PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        document.add(table);
        // Start a new page
        document.newPage();

        HTMLWorker htmlWorker = new HTMLWorker(document);
        htmlWorker.parse(new StringReader(contract.getRemark()));
        // Start a new page
        document.newPage();

        document.add(new Paragraph("Review Board", font18n));
        document.add(new LineSeparator(0.5f, 100, null, 0, -5));

        table = new PdfPTable(3);
        table.setWidthPercentage(100);

        cell = new PdfPCell(new Paragraph("Review Board", font18n));
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Date", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review", font12n));
        table.addCell(cell);
        for (HistoryContractEntity history : historyContractService.listing(contract)) {
            cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getReview(), font8n));
            table.addCell(cell);
        }
        document.add(table);

        document.close();

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.reset();
        response.addHeader("Content-Type", "application/force-download");
        String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8");
        //            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
        response.getOutputStream().write(output.toByteArray());
        response.getOutputStream().flush();
        context.responseComplete();
        context.renderResponse();

    } catch (BadPdfFormatException | IOException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:es.gob.afirma.signers.pades.ltv.PdfDocumentSecurityStore.java

License:Open Source License

/** Constructor para inicializar la clase con una estructura DSS ya creada.
 * @param dss Diccionario DSS/*from   w  w  w  . j a  v a  2s  . c o  m*/
 * @throws IOException En caso de errores de entrada / salida */
PdfDocumentSecurityStore(final PdfDictionary dss) throws IOException {
    int i = 0;
    PdfArray arrayCerts = dss.getAsArray(new PdfName(PDF_NAME_CERTS));
    if (arrayCerts != null) {
        for (final Iterator<PdfObject> iterator = arrayCerts.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.certificates.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayOcsps = dss.getAsArray(new PdfName(PDF_NAME_OCSPS));
    if (arrayOcsps != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayOcsps.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.ocsps.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    PdfArray arrayCrls = dss.getAsArray(new PdfName(PDF_NAME_CRLS));
    if (arrayCrls != null) {
        i = 0;
        for (final Iterator<PdfObject> iterator = arrayCrls.listIterator(); iterator.hasNext();) {
            final PdfIndirectReference reference = (PdfIndirectReference) iterator.next();
            this.crls.put(Integer.valueOf(i),
                    getContentBytesFromContentObject(PdfReader.getPdfObject(reference)));
            i++;
        }

    }
    final PdfDictionary vri = dss.getAsDict(new PdfName(PDF_NAME_VRI));
    if (vri != null) {
        PdfName key;
        ValidationInformation val;
        for (final Iterator<PdfName> iterator = vri.getKeys().iterator(); iterator.hasNext(); this.signatures
                .put(key.toString().substring(1), val)) {
            key = iterator.next();
            final PdfDictionary vriEntry = vri.getAsDict(key);
            arrayCerts = vriEntry.getAsArray(new PdfName(PDF_NAME_CERT));
            int certId[];
            if (arrayCerts != null) {
                certId = new int[arrayCerts.size()];
                for (i = 0; i < arrayCerts.size(); i++) {
                    final PdfIndirectReference reference = (PdfIndirectReference) arrayCerts.getPdfObject(i);
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.certificates.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.certificates.get(Integer.valueOf(index)))) {
                            certId[i] = index;
                        }
                    } while (true);
                }

            } else {
                certId = new int[0];
            }
            arrayOcsps = vriEntry.getAsArray(new PdfName(PDF_NAME_OCSP));
            int ocspId[];
            if (arrayOcsps != null) {
                ocspId = new int[arrayOcsps.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorOcsps = arrayOcsps.listIterator(); iteratorOcsps
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorOcsps.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.ocsps.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.ocsps.get(Integer.valueOf(index)))) {
                            ocspId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                ocspId = new int[0];
            }
            arrayCrls = vriEntry.getAsArray(new PdfName(PDF_NAME_CRL));
            int crlId[];
            if (arrayCrls != null) {
                crlId = new int[arrayCrls.size()];
                i = 0;
                for (final Iterator<PdfObject> iteratorCRLs = arrayCrls.listIterator(); iteratorCRLs
                        .hasNext();) {
                    final PdfIndirectReference reference = (PdfIndirectReference) iteratorCRLs.next();
                    final byte referenceBytes[] = getContentBytesFromContentObject(
                            PdfReader.getPdfObject(reference));
                    final Iterator<Integer> iteratorKeys = this.crls.keySet().iterator();
                    do {
                        if (!iteratorKeys.hasNext()) {
                            break;
                        }
                        final int index = iteratorKeys.next().intValue();
                        if (Arrays.equals(referenceBytes, this.crls.get(Integer.valueOf(index)))) {
                            crlId[i] = index;
                        }
                    } while (true);
                    i++;
                }

            } else {
                crlId = new int[0];
            }
            Calendar date = null;
            if (vriEntry.get(PdfName.TU) != null) {
                if (vriEntry.get(PdfName.TU) instanceof PdfDate) {
                    date = PdfDate.decode(((PdfDate) vriEntry.get(PdfName.TU)).getEncoding());
                }
                if (vriEntry.get(PdfName.TU) instanceof PdfString) {
                    date = PdfDate.decode(vriEntry.getAsString(PdfName.TU).getEncoding());
                }
            }
            val = new ValidationInformation(key, certId, ocspId, crlId, date);
        }
    }
}

From source file:es.gob.afirma.signers.pades.PAdESSigner.java

License:Open Source License

@SuppressWarnings("boxing")
static byte[] signPDF(final PrivateKey key, final java.security.cert.Certificate[] certChain,
        final byte[] inPDF, final Properties extraParams, final String algorithm)
        throws IOException, AOException, DocumentException, NoSuchAlgorithmException, CertificateException {

    // *********************************************************************************************************************
    // **************** LECTURA PARAMETROS ADICIONALES *********************************************************************
    // *********************************************************************************************************************

    // Imagen de la rubrica
    final Image rubric = getRubricImage(extraParams.getProperty("signatureRubricImage")); //$NON-NLS-1$

    // Usar hora y fecha del sistema
    final boolean useSystemDateTime = Boolean
            .parseBoolean(extraParams.getProperty("applySystemDate", Boolean.TRUE.toString())); //$NON-NLS-1$

    // Motivo de la firma
    final String reason = extraParams.getProperty("signReason"); //$NON-NLS-1$

    // Nombre del campo de firma preexistente en el PDF a usar
    final String signatureField = extraParams.getProperty("signatureField"); //$NON-NLS-1$

    // Lugar de realizacion de la firma
    final String signatureProductionCity = extraParams.getProperty("signatureProductionCity"); //$NON-NLS-1$

    // Datos de contacto (correo electronico) del firmante
    final String signerContact = extraParams.getProperty("signerContact"); //$NON-NLS-1$

    // Pagina donde situar la firma visible
    int page = LAST_PAGE;
    try {/*from   w w  w . j  av a  2  s . c  om*/
        page = Integer.parseInt(extraParams.getProperty("signaturePage")); //$NON-NLS-1$
    } catch (final Exception e) {
        /* Se deja la pagina tal y como esta */
    }

    // Nombre del subfiltro de firma en el diccionario PDF
    final String signatureSubFilter = extraParams.getProperty("signatureSubFilter"); //$NON-NLS-1$

    // ******************
    // ** Adjuntos ******

    // Contenido a adjuntar (en Base64)
    final String b64Attachment = extraParams.getProperty("attach"); //$NON-NLS-1$

    // Nombre que se pondra al fichero adjunto en el PDF
    final String attachmentFileName = extraParams.getProperty("attachFileName"); //$NON-NLS-1$

    // Descripcion del adjunto
    final String attachmentDescription = extraParams.getProperty("attachDescription"); //$NON-NLS-1$

    // ** Fin Adjuntos **
    // ******************

    // Nivel de certificacion del PDF
    int certificationLevel;
    try {
        certificationLevel = extraParams.getProperty("certificationLevel") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("certificationLevel")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        certificationLevel = UNDEFINED;
    }

    // *****************************
    // **** Texto firma visible ****

    // Texto en capa 4
    final String layer4Text = extraParams.getProperty("layer4Text"); //$NON-NLS-1$

    // Texto en capa 2
    final String layer2Text = extraParams.getProperty("layer2Text"); //$NON-NLS-1$

    // Tipo de letra en capa 2
    int layer2FontFamily;
    try {
        layer2FontFamily = extraParams.getProperty("layer2FontFamily") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontFamily")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontFamily = UNDEFINED;
    }

    // Tamano del tipo de letra en capa 2
    int layer2FontSize;
    try {
        layer2FontSize = extraParams.getProperty("layer2FontSize") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontSize")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontSize = UNDEFINED;
    }

    // Estilo del tipo de letra en capa 2
    int layer2FontStyle;
    try {
        layer2FontStyle = extraParams.getProperty("layer2FontStyle") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontStyle")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontStyle = UNDEFINED;
    }

    // Color del tipo de letra en capa 2
    final String layer2FontColor = extraParams.getProperty("layer2FontColor"); //$NON-NLS-1$

    // ** Fin texto firma visible **
    // *****************************

    // Contrasena del propietario del PDF
    String ownerPassword = extraParams.getProperty("ownerPassword"); //$NON-NLS-1$

    // Contrasena del usuario del PDF
    final String userPassword = extraParams.getProperty("userPassword"); //$NON-NLS-1$

    // *********************************************************************************************************************
    // **************** FIN LECTURA PARAMETROS ADICIONALES *****************************************************************
    // *********************************************************************************************************************

    PdfReader pdfReader;
    try {
        if (ownerPassword != null) {
            pdfReader = new PdfReader(inPDF, ownerPassword.getBytes());
        } else if (userPassword != null) {
            pdfReader = new PdfReader(inPDF, userPassword.getBytes());
        } else {
            pdfReader = new PdfReader(inPDF);
        }
    } catch (final BadPasswordException e) {
        // Comprobamos que el signer esta en modo interactivo, y si no lo
        // esta no pedimos contrasena por dialogo, principalmente para no interrumpir un firmado por lotes
        // desatendido
        if (Boolean.TRUE.toString().equalsIgnoreCase(extraParams.getProperty("headLess"))) { //$NON-NLS-1$
            throw new BadPdfPasswordException(e);
        }
        // La contrasena que nos han proporcionada no es buena o no nos
        // proporcionaron ninguna
        ownerPassword = new String(AOUIFactory.getPassword(
                ownerPassword == null ? PDFMessages.getString("AOPDFSigner.0") //$NON-NLS-1$
                        : PDFMessages.getString("AOPDFSigner.1"), //$NON-NLS-1$
                null));
        try {
            pdfReader = new PdfReader(inPDF, ownerPassword.getBytes());
        } catch (final BadPasswordException e2) {
            throw new BadPdfPasswordException(e2);
        }
    } catch (final IOException e) {
        throw new InvalidPdfException(e);
    }

    if (pdfReader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
            && !Boolean.parseBoolean(extraParams.getProperty("allowSigningCertifiedPdfs"))) { //$NON-NLS-1$
        // Si no permitimos dialogos graficos o directamente hemos indicado que no permitimos firmar PDF certificados lanzamos
        // una excepcion
        if (Boolean.parseBoolean(extraParams.getProperty("headLess")) //$NON-NLS-1$
                || "false".equalsIgnoreCase(extraParams.getProperty("allowSigningCertifiedPdfs"))) { //$NON-NLS-1$ //$NON-NLS-2$
            throw new PdfIsCertifiedException();
        }
        // En otro caso, perguntamos al usuario
        if (AOUIFactory.NO_OPTION == AOUIFactory.showConfirmDialog(null, PDFMessages.getString("AOPDFSigner.8"), //$NON-NLS-1$
                PDFMessages.getString("AOPDFSigner.9"), //$NON-NLS-1$
                AOUIFactory.YES_NO_OPTION, AOUIFactory.WARNING_MESSAGE)) {
            throw new AOCancelledOperationException(
                    "El usuario no ha permitido la firma de un PDF certificado"); //$NON-NLS-1$
        }
    }

    // Los derechos van firmados por Adobe, y como desde iText se invalidan
    // es mejor quitarlos
    pdfReader.removeUsageRights();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Activar el atributo de "agregar firma" (cuarto parametro del metodo
    // "PdfStamper.createSignature") hace que se cree una nueva revision del
    // documento y evita que las firmas previas queden invalidadas. Sin embargo, este
    // exige que el PDF no incorpore ningun error, asi que lo mantendremos desactivado
    // para la primera firma y activado para las subsiguientes. Un error incorporado
    // en un PDF erroneo puede quedar subsanado en su version firmada, haciendo
    // posible incorporar nuevas firmas agregando revisiones del documento.
    final PdfStamper stp;
    try {
        stp = PdfStamper.createSignature(pdfReader, // PDF de entrada
                baos, // Salida
                '\0', // Mantener version
                null, // No crear temporal
                pdfReader.getAcroFields().getSignatureNames().size() > 0 // Si hay mas firmas, creo una revision
        );
    } catch (final BadPasswordException e) {
        throw new PdfIsPasswordProtectedException(e);
    }

    // Aplicamos todos los atributos de firma
    final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    stp.setFullCompression();
    sap.setAcro6Layers(true);

    // PAdES parte 3 seccion 4.7 - Habilitacion para LTV
    stp.getWriter().addDeveloperExtension(new PdfDeveloperExtension(new PdfName("ESIC"), //$NON-NLS-1$
            PdfWriter.PDF_VERSION_1_7, 1));

    // Adjuntos
    if (b64Attachment != null && attachmentFileName != null) {
        byte[] attachment = null;
        try {
            attachment = Base64.decode(b64Attachment);
        } catch (final IOException e) {
            LOGGER.warning("Se ha indicado un adjunto, pero no estaba en formato Base64, se ignorara : " + e); //$NON-NLS-1$
        }
        if (attachment != null) {
            stp.getWriter().addFileAttachment(attachmentDescription, attachment, null, attachmentFileName);
        }
    }

    // iText antiguo
    sap.setRender(PdfSignatureAppearance.SignatureRenderDescription);
    // En iText nuevo seria "sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);"

    // Razon de firma
    if (reason != null) {
        sap.setReason(reason);
    }

    // Establecer fecha local del equipo
    if (useSystemDateTime) {
        sap.setSignDate(new GregorianCalendar());
    }

    // Gestion de los cifrados
    if (pdfReader.isEncrypted() && (ownerPassword != null || userPassword != null)) {
        if (Boolean.TRUE.toString().equalsIgnoreCase(extraParams.getProperty("avoidEncryptingSignedPdfs"))) { //$NON-NLS-1$
            LOGGER.info(
                    "Aunque el PDF original estaba encriptado no se encriptara el PDF firmado (se establecio el indicativo 'avoidEncryptingSignedPdfs')" //$NON-NLS-1$
            );
        } else {
            LOGGER.info("El PDF original estaba encriptado, se intentara encriptar tambien el PDF firmado" //$NON-NLS-1$
            );
            try {
                stp.setEncryption(ownerPassword != null ? ownerPassword.getBytes() : null,
                        userPassword != null ? userPassword.getBytes() : null, pdfReader.getPermissions(),
                        pdfReader.getCryptoMode());
            } catch (final DocumentException de) {
                LOGGER.warning("No se ha podido cifrar el PDF destino, se escribira sin contrasena: " + de //$NON-NLS-1$
                );
            }
        }
    }

    // Pagina en donde se imprime la firma
    if (page == LAST_PAGE) {
        page = pdfReader.getNumberOfPages();
    }

    // Posicion de la firma
    final Rectangle signaturePositionOnPage = getSignaturePositionOnPage(extraParams);
    if (signaturePositionOnPage != null && signatureField == null) {
        sap.setVisibleSignature(signaturePositionOnPage, page, null);
    } else if (signatureField != null) {
        sap.setVisibleSignature(signatureField);
    }

    // Localizacion en donde se produce la firma
    if (signatureProductionCity != null) {
        sap.setLocation(signatureProductionCity);
    }

    // Contacto del firmante
    if (signerContact != null) {
        sap.setContact(signerContact);
    }

    // Rubrica de la firma
    if (rubric != null) {
        sap.setImage(rubric);
        sap.setLayer2Text(""); //$NON-NLS-1$
        sap.setLayer4Text(""); //$NON-NLS-1$
    }

    // **************************
    // ** Texto en las capas ****
    // **************************

    // Capa 2
    if (layer2Text != null) {

        sap.setLayer2Text(layer2Text);

        final int layer2FontColorR;
        final int layer2FontColorG;
        final int layer2FontColorB;
        if ("black".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("white".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 255;
            layer2FontColorB = 255;
        } else if ("lightGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 192;
            layer2FontColorG = 192;
            layer2FontColorB = 192;
        } else if ("gray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 128;
            layer2FontColorG = 128;
            layer2FontColorB = 128;
        } else if ("darkGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 64;
            layer2FontColorG = 64;
            layer2FontColorB = 64;
        } else if ("red".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("pink".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 175;
            layer2FontColorB = 175;
        } else if (layer2FontColor == null) {
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else {
            LOGGER.warning("No se soporta el color '" + layer2FontColor //$NON-NLS-1$
                    + "' para el texto de la capa 4, se usara negro"); //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        }

        com.lowagie.text.Font font;
        try {
            Class<?> colorClass;
            if (Platform.getOS() == OS.ANDROID) {
                colorClass = Class.forName("harmony.java.awt.Color"); //$NON-NLS-1$
            } else {
                colorClass = Class.forName("java.awt.Color"); //$NON-NLS-1$
            }
            final Object color = colorClass.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE)
                    .newInstance(layer2FontColorR, layer2FontColorG, layer2FontColorB);

            font = com.lowagie.text.Font.class
                    .getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE, colorClass).newInstance(
                            // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                            layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                            // Size (DEFAULTSIZE = 12)
                            layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                            // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                            layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                            // Color
                            color);

        } catch (Exception e) {
            font = new com.lowagie.text.Font(
                    // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                    layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                    // Size (DEFAULTSIZE = 12)
                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                    // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                    layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                    // Color
                    null);
        }
        sap.setLayer2Font(font);
    }

    // Capa 4
    if (layer4Text != null) {
        sap.setLayer4Text(layer4Text);
    }

    // ***************************
    // ** Fin texto en las capas *
    // ***************************

    sap.setCrypto(null, certChain, null, null);

    final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
            signatureSubFilter != null && !"".equals(signatureSubFilter) ? new PdfName(signatureSubFilter) //$NON-NLS-1$
                    : PdfName.ADBE_PKCS7_DETACHED);

    // Fecha de firma
    if (sap.getSignDate() != null) {
        dic.setDate(new PdfDate(sap.getSignDate()));
    }

    dic.setName(PdfPKCS7.getSubjectFields((X509Certificate) certChain[0]).getField("CN")); //$NON-NLS-1$
    if (sap.getReason() != null) {
        dic.setReason(sap.getReason());
    }

    // Lugar de la firma
    if (sap.getLocation() != null) {
        dic.setLocation(sap.getLocation());
    }

    // Contacto del firmante
    if (sap.getContact() != null) {
        dic.setContact(sap.getContact());
    }

    sap.setCryptoDictionary(dic);

    // Certificacion del PDF (NOT_CERTIFIED = 0, CERTIFIED_NO_CHANGES_ALLOWED = 1,
    // CERTIFIED_FORM_FILLING = 2, CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = 3)
    if (certificationLevel != -1) {
        sap.setCertificationLevel(certificationLevel);
    }

    // Reservamos el espacio necesario en el PDF para insertar la firma
    final HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, Integer.valueOf(CSIZE * 2 + 2));

    sap.preClose(exc);

    // ********************************************************************************
    // **************** CALCULO DEL SIGNED DATA ***************************************
    // ********************************************************************************

    // La norma PAdES establece que si el algoritmo de huella digital es SHA1 debe usarse SigningCertificateV2, y en cualquier
    // otro caso deberia usarse SigningCertificateV2
    boolean signingCertificateV2;
    if (extraParams.containsKey("signingCertificateV2")) { //$NON-NLS-1$
        signingCertificateV2 = Boolean.parseBoolean(extraParams.getProperty("signingCertificateV2")); //$NON-NLS-1$
    } else {
        signingCertificateV2 = !"SHA1".equals(AOSignConstants.getDigestAlgorithmName(algorithm)); //$NON-NLS-1$
    }

    byte[] completeCAdESSignature = GenCAdESEPESSignedData.generateSignedData(
            new P7ContentSignerParameters(inPDF, algorithm), true, // omitContent
            new AdESPolicy(extraParams), signingCertificateV2, key, certChain,
            MessageDigest.getInstance(AOSignConstants.getDigestAlgorithmName(algorithm))
                    .digest(AOUtil.getDataFromInputStream(sap.getRangeStream())),
            AOSignConstants.getDigestAlgorithmName(algorithm), true, // Modo PAdES
            PDF_OID,
            extraParams.getProperty("contentDescription") != null //$NON-NLS-1$
                    ? extraParams.getProperty("contentDescription") //$NON-NLS-1$
                    : PDF_DESC);

    //***************** SELLO DE TIEMPO ****************
    final String tsa = extraParams.getProperty("tsaURL"); //$NON-NLS-1$
    URI tsaURL;
    if (tsa != null) {
        try {
            tsaURL = new URI(tsa);
        } catch (final Exception e) {
            LOGGER.warning("Se ha indicado una URL de TSA invalida (" + tsa //$NON-NLS-1$
                    + "), no se anadira sello de tiempo: " + e); //$NON-NLS-1$
            tsaURL = null;
        }
        if (tsaURL != null) {
            final String tsaPolicy = extraParams.getProperty("tsaPolicy"); //$NON-NLS-1$
            if (tsaPolicy == null) {
                LOGGER.warning(
                        "Se ha indicado una URL de TSA pero no una politica, no se anadira sello de tiempo"); //$NON-NLS-1$
            } else {
                final String tsaHashAlgorithm = extraParams.getProperty("tsaHashAlgorithm"); //$NON-NLS-1$
                completeCAdESSignature = new CMSTimestamper(
                        !Boolean.FALSE.toString().equalsIgnoreCase(extraParams.getProperty("tsaRequireCert")), //$NON-NLS-1$
                        tsaPolicy, tsaURL, extraParams.getProperty("tsaUsr"), //$NON-NLS-1$
                        extraParams.getProperty("tsaPwd"), //$NON-NLS-1$
                        extraParams.getProperty("tsaExtensionOid") != null //$NON-NLS-1$
                                && extraParams.getProperty("tsaExtensionValueBase64") != null ? //$NON-NLS-1$
                                        new TsaRequestExtension[] { new TsaRequestExtension(
                                                extraParams.getProperty("tsaExtensionOid"), //$NON-NLS-1$
                                                Boolean.getBoolean(extraParams
                                                        .getProperty("tsaExtensionCritical", "false")), //$NON-NLS-1$ //$NON-NLS-2$
                                                Base64.decode(
                                                        extraParams.getProperty("tsaExtensionValueBase64")) //$NON-NLS-1$
                                        ) } : null).addTimestamp(completeCAdESSignature,
                                                AOAlgorithmID.getOID(AOSignConstants.getDigestAlgorithmName(
                                                        tsaHashAlgorithm != null ? tsaHashAlgorithm : "SHA1"))); //$NON-NLS-1$
            }
        }

    }
    //************** FIN SELLO DE TIEMPO ****************

    // ********************************************************************************
    // *************** FIN CALCULO DEL SIGNED DATA ************************************
    // ********************************************************************************

    final byte[] outc = new byte[CSIZE];
    if (outc.length < completeCAdESSignature.length) {
        throw new AOException("La firma generada tiene un tamano (" + completeCAdESSignature.length //$NON-NLS-1$
                + ") mayor que el permitido (" + outc.length + ")" //$NON-NLS-1$ //$NON-NLS-2$
        );
    }
    final PdfDictionary dic2 = new PdfDictionary();
    System.arraycopy(completeCAdESSignature, 0, outc, 0, completeCAdESSignature.length);
    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

    sap.close(dic2);

    return baos.toByteArray();
}

From source file:es.gob.afirma.signers.pades.PdfSessionManager.java

License:Open Source License

/** Obtiene los datos PDF relevantes en cuanto a las firmas electr&oacute;nicas, consistentes en los datos
 * a ser firmados con CAdES o PKCS#7 y los metadatos necesarios para su correcta inserci&oacute;n en el PDF.
 * @param inPDF Documento PDF que se desea firmar
 * @param certChain Cadena de certificados del firmante
 * @param signTime Hora de la firma/*from  ww  w  . j av  a2 s .  co  m*/
 * @param extraParams Par&aacute;metros adicionales de la firma
 * @return Datos PDF relevantes en cuanto a las firmas electr&oacute;nicas
 * @throws AOException En caso de que ocurra cualquier otro tipo de error
 * @throws IOException En caso de errores de entrada / salida
 * @throws DocumentException Si ocurren errores en la estampaci&iacute;n de la firma PDF */
public static PdfTriPhaseSession getSessionData(final byte[] inPDF, final Certificate[] certChain,
        final Calendar signTime, final Properties extraParams)
        throws AOException, IOException, DocumentException {

    // *********************************************************************************************************************
    // **************** LECTURA PARAMETROS ADICIONALES *********************************************************************
    // *********************************************************************************************************************

    // Forzar la creacion de revisiones incluso en PDF no firmados
    final boolean alwaysCreateRevision = Boolean
            .parseBoolean(extraParams.getProperty("alwaysCreateRevision", "true")); //$NON-NLS-1$ //$NON-NLS-2$

    // Imagen de la rubrica
    final Image rubric = PdfPreProcessor.getImage(extraParams.getProperty("signatureRubricImage")); //$NON-NLS-1$

    // Motivo de la firma
    final String reason = extraParams.getProperty("signReason"); //$NON-NLS-1$

    // Nombre del campo de firma preexistente en el PDF a usar
    final String signatureField = extraParams.getProperty("signatureField"); //$NON-NLS-1$

    // Lugar de realizacion de la firma
    final String signatureProductionCity = extraParams.getProperty("signatureProductionCity"); //$NON-NLS-1$

    // Datos de contacto (correo electronico) del firmante
    final String signerContact = extraParams.getProperty("signerContact"); //$NON-NLS-1$

    // Pagina donde situar la firma visible
    int page = LAST_PAGE;
    try {
        page = Integer.parseInt(extraParams.getProperty("signaturePage")); //$NON-NLS-1$
    } catch (final Exception e) {
        /* Se deja la pagina tal y como esta */
    }

    // Nombre del subfiltro de firma en el diccionario PDF
    final String signatureSubFilter = extraParams.getProperty("signatureSubFilter"); //$NON-NLS-1$

    // Nivel de certificacion del PDF
    int certificationLevel;
    try {
        certificationLevel = extraParams.getProperty("certificationLevel") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("certificationLevel")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        certificationLevel = UNDEFINED;
    }

    // *****************************
    // **** Texto firma visible ****

    // Texto en capa 4
    final String layer4Text = extraParams.getProperty("layer4Text"); //$NON-NLS-1$

    // Texto en capa 2
    final String layer2Text = extraParams.getProperty("layer2Text"); //$NON-NLS-1$

    // Tipo de letra en capa 2
    int layer2FontFamily;
    try {
        layer2FontFamily = extraParams.getProperty("layer2FontFamily") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontFamily")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontFamily = UNDEFINED;
    }

    // Tamano del tipo de letra en capa 2
    int layer2FontSize;
    try {
        layer2FontSize = extraParams.getProperty("layer2FontSize") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontSize")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontSize = UNDEFINED;
    }

    // Estilo del tipo de letra en capa 2
    int layer2FontStyle;
    try {
        layer2FontStyle = extraParams.getProperty("layer2FontStyle") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontStyle")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontStyle = UNDEFINED;
    }

    // Color del tipo de letra en capa 2
    final String layer2FontColor = extraParams.getProperty("layer2FontColor"); //$NON-NLS-1$

    // ** Fin texto firma visible **
    // *****************************

    // *********************************************************************************************************************
    // **************** FIN LECTURA PARAMETROS ADICIONALES *****************************************************************
    // *********************************************************************************************************************

    final PdfReader pdfReader = PdfUtil.getPdfReader(inPDF, extraParams,
            Boolean.getBoolean(extraParams.getProperty("headLess")) //$NON-NLS-1$
    );

    //PdfUtil.checkPdfCertification(pdfReader.getCertificationLevel(), extraParams);
    //PdfUtil.checkUnregisteredSignatures(pdfReader, extraParams);

    // Los derechos van firmados por Adobe, y como desde iText se invalidan
    // es mejor quitarlos
    pdfReader.removeUsageRights();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Activar el atributo de "agregar firma" (quinto parametro del metodo
    // "PdfStamper.createSignature") hace que se cree una nueva revision del
    // documento y evita que las firmas previas queden invalidadas.
    // Sin embargo, este procedimiento no funciona cuando los PDF contienen informacion
    // despues de la ultima marca %%EOF, aspecto no permitido en PDF 1.7 (ISO 32000-1:2008)
    // pero si en PDF 1.3 (Adobe) y que se da con frecuencia en PDF generados con bibliotetcas
    // de software libre como QPDF.
    //
    //  Especificacion PDF 1.3
    //   3.4.4, "File Trailer"
    //     Acrobat viewers require only that the %%EOF marker appear somewhere within
    //     the last 1024 bytes of the file.
    //
    //  Especificacion PDF 1.7
    //   7.5.5. File Trailer
    //     The trailer of a PDF file enables a conforming reader to quickly find the
    //     cross-reference table and certain special objects. Conforming readers should read a
    //     PDF file from its end. The last line of the file shall contain only the end-of-file
    //     marker, %%EOF.
    //
    // Para aceptar al menos en algunos casos PDF 1.3 (son aun muy frecuentes, especialmente
    // en archivos, lo mantendremos desactivado para la primera firma y activado para las
    // subsiguientes.
    //
    // No obstante, el integrador puede siempre forzar la creacion de revisiones mediante
    // el parametro "alwaysCreateRevision".
    final PdfStamper stp;
    try {
        stp = PdfStamper.createSignature(
                // PDF de entrada
                pdfReader,
                // Salida
                baos,
                // Mantener version
                '\0',
                // No crear temporal
                null,
                // Si hay mas firmas o asi me lo indican, creo una revision
                alwaysCreateRevision || pdfReader.getAcroFields().getSignatureNames().size() > 0,
                // Momento de la firma
                signTime);
    } catch (final BadPasswordException e) {
        // Comprobamos que el signer esta en modo interactivo, y si no lo
        // esta no pedimos contrasena por dialogo, principalmente para no interrumpir un firmado por lotes
        // desatendido
        if (Boolean.getBoolean(extraParams.getProperty("headLess"))) { //$NON-NLS-1$
            throw new BadPdfPasswordException(e);
        }
        // La contrasena que nos han proporcionada no es buena o no nos
        // proporcionaron ninguna
        final String userPwd = new String(AOUIFactory.getPassword(
                extraParams.getProperty("userPassword") == null ? CommonPdfMessages.getString("AOPDFSigner.0") //$NON-NLS-1$//$NON-NLS-2$
                        : CommonPdfMessages.getString("AOPDFSigner.1"), //$NON-NLS-1$
                null));
        if ("".equals(userPwd)) { //$NON-NLS-1$
            throw new AOCancelledOperationException("Entrada de contrasena de PDF cancelada por el usuario", e //$NON-NLS-1$
            );
        }
        extraParams.put("userPassword", userPwd); //$NON-NLS-1$
        return getSessionData(inPDF, certChain, signTime, extraParams);
    }

    // Aplicamos todos los atributos de firma
    final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    stp.setFullCompression();
    sap.setAcro6Layers(true);

    PdfUtil.enableLtv(stp);

    // Adjuntos
    PdfPreProcessor.attachFile(extraParams, stp);

    // Imagenes
    PdfPreProcessor.addImage(extraParams, stp);

    // Establecemos el render segun iText antiguo, varia en versiones modernas
    sap.setRender(PdfSignatureAppearance.SignatureRenderDescription);

    // Razon de firma
    if (reason != null) {
        sap.setReason(reason);
    }

    sap.setSignDate(signTime);

    // Gestion de los cifrados
    PdfUtil.managePdfEncryption(stp, pdfReader, extraParams);

    // Pagina en donde se imprime la firma
    if (page == LAST_PAGE) {
        page = pdfReader.getNumberOfPages();
    }

    // Posicion de la firma
    final Rectangle signaturePositionOnPage = getSignaturePositionOnPage(extraParams);
    if (signaturePositionOnPage != null && signatureField == null) {
        sap.setVisibleSignature(signaturePositionOnPage, page, null);
    } else if (signatureField != null) {
        sap.setVisibleSignature(signatureField);
    }

    // Localizacion en donde se produce la firma
    if (signatureProductionCity != null) {
        sap.setLocation(signatureProductionCity);
    }

    // Contacto del firmante
    if (signerContact != null) {
        sap.setContact(signerContact);
    }

    // Rubrica de la firma
    if (rubric != null) {
        sap.setImage(rubric);
        sap.setLayer2Text(""); //$NON-NLS-1$
        sap.setLayer4Text(""); //$NON-NLS-1$
    }

    // **************************
    // ** Texto en las capas ****
    // **************************

    // Capa 2
    if (layer2Text != null) {

        sap.setLayer2Text(layer2Text);

        final int layer2FontColorR;
        final int layer2FontColorG;
        final int layer2FontColorB;

        if ("black".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("white".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 255;
            layer2FontColorB = 255;
        } else if ("lightGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 192;
            layer2FontColorG = 192;
            layer2FontColorB = 192;
        } else if ("gray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 128;
            layer2FontColorG = 128;
            layer2FontColorB = 128;
        } else if ("darkGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 64;
            layer2FontColorG = 64;
            layer2FontColorB = 64;
        } else if ("red".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("pink".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 175;
            layer2FontColorB = 175;
        } else if (layer2FontColor == null) {
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else {
            LOGGER.warning("No se soporta el color '" + layer2FontColor //$NON-NLS-1$
                    + "' para el texto de la capa 4, se usara negro"); //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        }

        com.lowagie.text.Font font;
        try {
            Class<?> colorClass;
            if (Platform.getOS() == OS.ANDROID) {
                colorClass = Class.forName("harmony.java.awt.Color"); //$NON-NLS-1$
            } else {
                colorClass = Class.forName("java.awt.Color"); //$NON-NLS-1$
            }
            final Object color = colorClass.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE)
                    .newInstance(Integer.valueOf(layer2FontColorR), Integer.valueOf(layer2FontColorG),
                            Integer.valueOf(layer2FontColorB));

            font = com.lowagie.text.Font.class
                    .getConstructor(Integer.TYPE, Float.TYPE, Integer.TYPE, colorClass).newInstance(
                            // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                            Integer.valueOf(layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily),
                            // Size (DEFAULTSIZE = 12)
                            Float.valueOf(
                                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize),
                            // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                            Integer.valueOf(layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL
                                    : layer2FontStyle),
                            // Color
                            color);
        } catch (final Exception e) {
            font = new com.lowagie.text.Font(
                    // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                    layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                    // Size (DEFAULTSIZE = 12)
                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                    // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                    layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                    // Color
                    null);
        }
        sap.setLayer2Font(font);
    }

    // Capa 4
    if (layer4Text != null) {
        sap.setLayer4Text(layer4Text);
    }

    // ***************************
    // ** Fin texto en las capas *
    // ***************************

    sap.setCrypto(null, certChain, null, null);

    final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
            signatureSubFilter != null && !"".equals(signatureSubFilter) ? new PdfName(signatureSubFilter) //$NON-NLS-1$
                    : PdfName.ADBE_PKCS7_DETACHED);

    // Fecha de firma
    if (sap.getSignDate() != null) {
        dic.setDate(new PdfDate(sap.getSignDate()));
    }

    dic.setName(PdfPKCS7.getSubjectFields((X509Certificate) certChain[0]).getField("CN")); //$NON-NLS-1$

    if (sap.getReason() != null) {
        dic.setReason(sap.getReason());
    }

    // Lugar de la firma
    if (sap.getLocation() != null) {
        dic.setLocation(sap.getLocation());
    }

    // Contacto del firmante
    if (sap.getContact() != null) {
        dic.setContact(sap.getContact());
    }

    sap.setCryptoDictionary(dic);

    // Certificacion del PDF (NOT_CERTIFIED = 0, CERTIFIED_NO_CHANGES_ALLOWED = 1,
    // CERTIFIED_FORM_FILLING = 2, CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = 3)
    if (certificationLevel != -1) {
        sap.setCertificationLevel(certificationLevel);
    }

    // Reservamos el espacio necesario en el PDF para insertar la firma
    final HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, Integer.valueOf(CSIZE * 2 + 2));

    sap.preClose(exc, signTime);

    final PdfObject pdfObject = ((com.lowagie.text.pdf.PdfStamperImp) stp.getWriter()).getFileID();

    return new PdfTriPhaseSession(sap, baos, new String(pdfObject.getBytes()));
}

From source file:eu.europa.cedefop.europass.jtool.util.ExtractAttachments.java

License:EUPL

/**
  * Extract the attachment file/*from  w  ww.j a v  a  2  s  .com*/
  * @throws Exception
  */
public void execute() throws Exception {
    boolean hasAttachment = false;
    try {
        PdfReader reader = new PdfReader(in);
        PdfDictionary catalog = reader.getCatalog();
        PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
        if (names != null) {
            PdfDictionary embFiles = (PdfDictionary) PdfReader
                    .getPdfObject(names.get(new PdfName("EmbeddedFiles")));
            if (embFiles != null) {
                HashMap embMap = PdfNameTree.readTree(embFiles);
                for (Iterator i = embMap.values().iterator(); i.hasNext();) {
                    PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                    unpackFile(filespec);
                }
            }
        }
        for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
            PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
            if (annots == null)
                continue;
            for (Iterator i = annots.listIterator(); i.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                if (!PdfName.FILEATTACHMENT.equals(subType))
                    continue;
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
                hasAttachment = true;
                unpackFile(filespec);
            }
        }
    } catch (Exception e) {
        log.error("Error while extracting PDF attachements: " + e);
    }
    if (!hasAttachment)
        throw new Exception("PDF file does not have attachment.");
}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileLTV.java

License:Open Source License

private PdfIndirectReference buildVRIDict(PdfStamper stamper, BasicOCSPResp crl) throws IOException {
    PdfIndirectReference ref = stamper.getWriter().getPdfIndirectReference();
    PdfDictionary ocspVriDictionary = new PdfDictionary();
    PdfDate vriDate = new PdfDate(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
    ocspVriDictionary.put(new PdfName("TU"), vriDate);

    // Other objects?

    stamper.getWriter().addToBody(ocspVriDictionary, ref, false);
    return ref;//from   w w  w .  j a  v a2  s . com
}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileLTV.java

License:Open Source License

private PdfIndirectReference buildVRIDict(PdfStamper stamper, X509CRL crl) throws IOException {
    PdfIndirectReference ref = stamper.getWriter().getPdfIndirectReference();
    PdfDictionary crlVriDictionary = new PdfDictionary();
    PdfDate vriDate = new PdfDate(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
    crlVriDictionary.put(new PdfName("TU"), vriDate);

    // Other objects?

    stamper.getWriter().addToBody(crlVriDictionary, ref, false);
    return ref;//from ww  w. j  ava2 s .co  m
}