Example usage for com.lowagie.text.pdf PdfStamper createSignature

List of usage examples for com.lowagie.text.pdf PdfStamper createSignature

Introduction

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

Prototype

public static PdfStamper createSignature(PdfReader reader, OutputStream os, char pdfVersion)
        throws DocumentException, IOException 

Source Link

Document

Applies a digital signature to a document.

Usage

From source file:SignPdf.java

License:Open Source License

/**
* Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
* pdf had the current content at the current point in time.
*
* @param originalPdf/*from   w  w w  . ja va 2s .  c  om*/
* @param targetPdf
* @param pk
* @param certChain
* @param revoked
* @param tsaAddress
* address of a rfc 3161 compatible timestamp server
* @param reason
* reason for the signature
* @param location
* location of signing
* @param contact
* emailaddress of the person who is signing
* @throws IOException
* @throws DocumentException
* @throws SignatureException
*/
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    Rectangle cropBox = reader.getCropBox(1);
    float width = 50;
    float height = 50;
    Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20,
            cropBox.getRight() - 20, cropBox.getTop() - 20);
    sap.setVisibleSignature(rectangle, 1, null);
    //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

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;//ww w .  j a  v  a2 s.  co 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 ww.  j a  va2  s  . com*/
    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 .j a  va 2 s.co  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());

    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.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

private void signDocument(String pdfFileName) {
    try {//w  ww  . j  a  v  a 2s .com
        // 1. copy
        File tmpPDFFile = new File(tmpDir, "tmp2PDF.pdf");
        copyFile(new File(pdfFileName), tmpPDFFile);
        // 2. sign
        KeyStore ks = KeyStore.getInstance(typeKeystore);
        FileInputStream fis = new FileInputStream(keystore);
        ks.load(fis, passwordKeystore.toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey(aliasCertificate, passwordKeystore.toCharArray());
        Certificate[] chain = ks.getCertificateChain(aliasCertificate);
        PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
        FileOutputStream fout = new FileOutputStream(pdfFileName);
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setVisibleSignature(new Rectangle(450, 730, 550, 780), 1, null);
        stp.close();
        fis.close();
    } catch (Exception e) {
        e.printStackTrace(Out.log);
    }
}

From source file:de.thorstenberger.examServer.pdf.signature.SignPdf.java

License:Open Source License

/**
 * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this
 * pdf had the current content at the current point in time.
 *
 * @param originalPdf/*from  ww  w.j  av a2  s  .  co m*/
 * @param targetPdf
 * @param pk
 * @param certChain
 * @param revoked
 * @param tsaAddress
 *          address of a rfc 3161 compatible timestamp server
 * @param reason
 *          reason for the signature
 * @param location
 *          location of signing
 * @param contact
 *          emailaddress of the person who is signing
 * @throws IOException
 * @throws DocumentException
 * @throws SignatureException
 */
public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf,
        final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress,
        final String reason, final String location, final String contact)
        throws IOException, DocumentException, SignatureException {
    // only an estimate, depends on the certificates returned by the TSA
    final int timestampSize = 4400;
    Security.addProvider(new BouncyCastleProvider());

    final PdfReader reader = new PdfReader(originalPdf);
    final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0');
    final PdfSignatureAppearance sap = stamper.getSignatureAppearance();

    // comment next lines to have an invisible signature
    sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null);
    sap.setLayer2Text("");

    final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC");
    final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>();

    // some informational fields
    sig.setReason(reason);
    sig.setLocation(location);
    sig.setContact(contact);
    sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN"));
    sig.setDate(new PdfDate(Calendar.getInstance()));

    // signing stuff
    final byte[] digest = new byte[256];
    final byte[] rsaData = new byte[20];
    sig.setExternalDigest(digest, rsaData, "RSA");
    sig.setSignInfo(pk, certChain, revoked);
    final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS);
    // *2 to get hex size, +2 for delimiters
    PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2);
    exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength()));
    sig.put(PdfName.CONTENTS, contentsLit);

    // certification; will display dialog or blue bar in Acrobat Reader

    sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

    // process all the information set above
    sap.setCryptoDictionary(sig);
    sap.preClose(exclusionSizes);

    // calculate digest (hash)
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buf = new byte[8192];
        int n;
        final InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) != -1) {
            messageDigest.update(buf, 0, n);
        }
        final byte[] hash = messageDigest.digest();

        // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA)
        final Signature sign = Signature.getInstance("SHA1withRSA");
        sign.initSign(pk);
        sign.update(hash);
        final byte[] signature = sign.sign();

        // prepare the location of the signature in the target PDF
        contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS);
        final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2];
        final PdfPKCS7 pkcs7 = sig.getSigner();
        pkcs7.setExternalDigest(signature, hash, "RSA");
        final PdfDictionary dic = new PdfDictionary();

        byte[] ssig = pkcs7.getEncodedPKCS7();
        try {
            // try to retrieve cryptographic timestamp from configured tsa server
            ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null);
        } catch (final RuntimeException e) {
            log.error("Could not retrieve timestamp from server.", e);
        }
        System.arraycopy(ssig, 0, outc, 0, ssig.length);

        // add the timestamped signature
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

        // finish up
        sap.close(dic);
    } catch (final InvalidKeyException e) {
        throw new RuntimeException("Internal implementation error! No such signature type.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException("Internal implementation error! No such algorithm type.", e);
    }
}

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

License:Open Source License

/**
 * Firma un archivo./*from  w ww .  java2s  . com*/
 * 
 * @param data
 * @return
 */
//   public void firmar(String claveToken,
//         String tipoCertificado, String urlCertificado, String path) {
public void firmar(String claveToken, String tipoCertificado, String path) {
    try {
        KeyStore keyStore = null;
        Enumeration<String> enumeration = null;
        String alias = null;
        PrivateKey privateKey = null;
        Certificate[] certs = null;
        CMSSignatureProcessor cms = null;
        KeyStoreProvider keyStoreProvider = null;
        try {
            if (tipoCertificado.equals("1") || tipoCertificado.equals("2") || tipoCertificado.equals("3")) {
                System.out.println("- Firmando con certificado token." + tipoCertificado);
                keyStoreProvider = this.getKeyStoreProvider(tipoCertificado);
                System.out.println(claveToken.toCharArray());
                keyStore = keyStoreProvider.getKeystore(claveToken.toCharArray());
                enumeration = keyStore.aliases();
                alias = enumeration.nextElement();
                privateKey = (PrivateKey) keyStore.getKey(alias, null);
                cms = new BouncyCastleSignatureProcessor(keyStore);
            }
            // if (tipoCertificado.equals("4")) {
            // System.out.println("- Firmando con certificado en archivo.");
            // keyStore = java.security.KeyStore.getInstance("PKCS12"); //
            // instancia el ks
            // keyStore.load(new java.io.FileInputStream(urlCertificado),
            // claveToken.toCharArray());
            // Enumeration en = keyStore.aliases();
            // alias = "";
            // Vector vectaliases = new Vector();
            // while (en.hasMoreElements()) {
            // vectaliases.add(en.nextElement());
            // }
            // String[] aliases = (String[]) (vectaliases.toArray(new
            // String[0]));
            // for (int i = 0; i < aliases.length; i++) {
            // if (keyStore.isKeyEntry(aliases[i])) {
            // alias = aliases[i];
            // break;
            // }
            // }
            // privateKey = (PrivateKey) keyStore.getKey(alias,
            // claveToken.toCharArray());
            // cms = new BouncyCastleSignatureProcessor(keyStore);
            // }
        } catch (Exception e) {
            System.out.println(" \n Fallo trayendo keystore " + e.getMessage());
        }
        certs = keyStore.getCertificateChain(alias);
        Certificate[] chain = keyStore.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) keyStore.getKey(alias, claveToken.toCharArray());
        String revocados = ""; // para verificar revocados
        revocados = verificaRevocados(((X509Certificate) certs[0]).getSerialNumber().toString(),
                tipoCertificado);
        if (!revocados.isEmpty()) {
            System.out.println(" CERTIFICADO REVOCADO " + revocados);
            return;
        }
        System.out.println("- Certificado valido ");

        PdfReader reader = new PdfReader(path);
        FileOutputStream fout = new FileOutputStream(path + ".Firmado.pdf");
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '?');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Firma Procesos Legales");
        sap.setLocation("RedTools");
        // Aade la firma visible. Podemos comentarla para que no sea
        // visible.
        sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
        stp.close();

        //         byte[] datosFirmados = cms.sign(data, privateKey, certs);
        System.out.println("Firmado Correctamente..!");
        //         this.datosUsuarioActual = this
        //               .crearDatosUsuario((X509Certificate) certs[0]); // llena la
        // clase de
        // tipo
        // datosUsuario
        // con el
        // certificado
        // actual

        //         return datosFirmados;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e); // FIXME
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * //from w  w w. ja  v a 2s  .c  om
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:questions.stamppages.CertificationSig.java

public static void main(String[] args) {

    PdfReader reader;//  w w w  . ja  v a2s  .c  o  m
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(KEYSTORE), "f00b4r".toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey("foobar", "r4b00f".toCharArray());
        Certificate[] chain = ks.getCertificateChain("foobar");
        reader = new PdfReader(RESOURCE);
        FileOutputStream os = new FileOutputStream(RESULT);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING);
        appearance.setReason("It's personal.");
        appearance.setLocation("Foobar");
        appearance.setVisibleSignature("Certifier_Signature");
        stamper.close();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:sos.util.security.SOSPDFSignatur.java

License:Apache License

/**
 * PDF Signatur erzeugen/*from   w  ww.j  a  v a2  s  . c  o m*/
 * 
 * @param privateKey      Private Key
 * @param chain            Certificate Chain
 * @param originalPdfName   Original PDF Datei zur Signierung
 * @param outputPdfName      Output (signierte) PDF Datei
 * @throws Exception
 */
public static void createSignatur(PrivateKey privateKey, Certificate[] chain, String originalPdfName,
        String outputPdfName) throws Exception {

    PdfReader reader = new PdfReader(originalPdfName);
    FileOutputStream fout = new FileOutputStream(outputPdfName);

    //createSignature(PdfReader reader, OutputStream os, char pdfVersion)
    //pdfVersion - the new pdf version or '\0' to keep the same version as
    // the original document

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

    //setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) 
    // CRL - certificate revocation lists (CRLs) that have different formats but important common uses.
    //       For example, all CRLs share the functionality of listing revoked certificates, and can be queried on whether or not they list a given certificate.
    // PdfName
    // SELF_SIGNED       -    The self signed filter
    // VERISIGN_SIGNED  -    The VeriSign filter
    // WINCER_SIGNED    -    The Windows Certificate Security
    sap.setCrypto(privateKey, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    //sap.setCrypto(privateKey, chain, null,PdfSignatureAppearance.WINCER_SIGNED);

    sap.setReason(SOSPDFSignatur.reason);
    sap.setContact(SOSPDFSignatur.contact);
    sap.setLocation(SOSPDFSignatur.location);

    //GregorianCalendar cal = new GregorianCalendar();
    //sap.setSignDate(cal);

    //             comment next line to have an invisible signature
    //setVisibleSignature(Rectangle pageRect, int page, String fieldName)

    //sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
    //sap.setVisibleSignature(new Rectangle(100,100,200, 200), 1, null);

    if (SOSPDFSignatur.visible) {// todo
        //sap.setVisibleSignature(new Rectangle(200, 200, 400, 400), 1, null);
    }

    stp.close();

}