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

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

Introduction

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

Prototype

public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion,
        File tempFile, final boolean append) throws DocumentException, IOException 

Source Link

Document

Applies a digital signature to a document, possibly as a new revision, making possible multiple signatures.

Usage

From source file:com.isa.firma.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {//from  w w  w. ja  va  2  s  .  c  o m
        System.out.println("Firma Controller::firmar");

        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        System.out.println("Pre definir apariencia...");
        if (infoFirma.isApariencia()) {
            System.out.println("Insertando apriencia en documento...");
            appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            appearance.setRenderingMode(Utiles.getModoApariencia());

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            //llx, lly, urx, ury
            String v = Utiles.encodingString(infoFirma.getFirmante());
            System.out.println("Post encoding: " + v);
            appearance.setLayer2Text(v);
            //appearance.setLayer2Text(  infoFirma.getFirmante() );
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

From source file:com.isa.firma.pades.FirmaPDFController.java

public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException {

    try {//from w ww  .j a  va2s  .  c  o  m
        PdfReader reader = new PdfReader(pdfbase64);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        if (infoFirma.isApariencia()) {
            System.out.println("Definiendo apariencia...");
            appearance.setRenderingMode(Utiles.getModoApariencia());

            if (!Utiles.getModoApariencia().equals(PdfSignatureAppearance.RenderingMode.DESCRIPTION)) {
                appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen())));
            }

            int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja();
            int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size();
            int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(),
                    infoFirma.getLargo());

            System.out.println("firmante: " + infoFirma.getFirmante());
            System.out.println("serie: " + infoFirma.getNroSerie());
            //llx, lly, urx, ury
            appearance.setLayer2Text(infoFirma.generarTextoEnFirma());
            appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]),
                    numeroPagFirma, "Id: " + IdGenerator.generate());
        }

        ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256",
                infoFirma.getProvidername());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0,
                CryptoStandard.CMS);

        System.out.println("PDF Firmado correctamente.");

        return os;

    } catch (IOException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (DocumentException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (KeyStoreException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex);
        throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause());
    }
}

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

License:Open Source License

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

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

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

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

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

    pdfSignatureAppearance.preClose(exc);

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

    return messageDigest.digest();
}

From source file:cz.hobrasoft.pdfmu.operation.args.OutPdfArgs.java

License:Open Source License

private void openStpSignature(PdfReader pdfReader, char pdfVersion) throws OperationException {
    assert os != null;
    assert stp == null;

    try {/*from  w ww . j av  a2s  .c  o  m*/
        // digitalsignatures20130304.pdf : Code sample 2.17
        // TODO?: Make sure version is high enough
        stp = PdfStamper.createSignature(pdfReader, os, pdfVersion, null, append);
    } catch (DocumentException | IOException ex) {
        throw new OperationException(OUTPUT_STAMPER_OPEN, ex,
                PdfmuUtils.sortedMap(new SimpleEntry<String, Object>("outputFile", file)));
    }
}

From source file:de.rub.dez6a3.jpdfsigner.control.ITextSigner.java

License:Open Source License

public ByteArrayOutputStream doSign(byte[] pdf, Rectangle stampPos, int pageNmbrForStamp) throws IOException,
        DocumentException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Certificate[] chain = signCert.toArray(new Certificate[0]);

    PdfReader reader = new PdfReader(pdf);
    ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
    PdfStamper stp = PdfStamper.createSignature(reader, byteOS, '\0', null, true);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    if (stampPos != null) {
        sap.setVisibleSignature(/*from   ww w  .  j a  v  a  2  s.  c om*/
                new com.itextpdf.text.Rectangle(stampPos.x, stampPos.y, stampPos.width, stampPos.height),
                pageNmbrForStamp, null);
        sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
        sap.setAcro6Layers(true);
    }
    //        Siganture Appearance

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    log.info("Creating signature with reason: " + ParamValidator.getInstance().getSignatureReason());
    sap.setReason(ParamValidator.getInstance().getSignatureReason());
    sap.setLocation("Ruhr-Universitt Bochum");
    Image i = Image.getInstance(getClass().getResource("/de/rub/dez6a3/jpdfsigner/resources/images/sign.png"));
    sap.setImage(i);
    sap.setCrypto((PrivateKey) signPrivKey, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    dic.setReason(ParamValidator.getInstance().getSignatureReason());
    dic.setLocation("Ruhr-Universitt Bochum");
    sap.setCryptoDictionary(dic);
    // preserve some space for the contents
    int contentEstimated = 15000;
    HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    sap.preClose(exc);
    // make the digest
    InputStream data = sap.getRangeStream();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte buf[] = new byte[8192];
    int n;
    while ((n = data.read(buf)) > 0) {
        messageDigest.update(buf, 0, n);
    }
    byte hash[] = messageDigest.digest();
    Calendar cal = Calendar.getInstance();
    // If we add a time stamp:
    TSAClient tsc = new TSAClientBouncyCastle("http://zeitstempel.dfn.de/");
    // Create the signature

    PdfPKCS7 sgn;
    try {
        sgn = new PdfPKCS7((PrivateKey) signPrivKey, chain, null, "SHA1", null, false);
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null);
        sgn.update(sh, 0, sh.length);
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, null);

        if (contentEstimated + 2 < encodedSig.length) {
            throw new DocumentException("Not enough space");
        }

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        // Replace the contents
        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
    }
    return byteOS;
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {/*from   w w w. j  a va  2 s .  c om*/
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

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

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*w  w  w.j a  v a2s.  co  m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

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

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON);
    Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE);
    Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC);

    boolean useSignatureField = false;
    String user = AuthenticationUtil.getRunAsUser();
    String positionType = "predefined";
    String positionLoc = "center";
    JSONObject box;
    int page = -1;

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

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

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

    // get the positioning type
    positionType = String.valueOf(positionObj.get("type"));

    // get the position (field or predefined)
    positionLoc = String.valueOf(positionObj.get("position"));

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

    int width = 350;
    int height = 75;

    File tempDir = null;

    // current date, used for both signing the PDF and creating the
    // associated signature object
    Calendar now = Calendar.getInstance();

    try {
        // get the keystore, pk and cert chain
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = keystore.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true);
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);

        // set reason for signature, location of signer, and date
        sap.setReason(reason);
        sap.setLocation(location);
        sap.setSignDate(now);

        // get the image for the signature
        BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height);
        // save the signature image back to the signatureProvider
        signatureProvider.saveSignatureImage(sigImage, signatureJson);

        if (visible) {
            //if this is a graphic sig, set the graphic here
            if (graphic) {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE));
            } else {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
            }

            // either insert the sig at a defined field or at a defined position / drawn loc
            if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null);
            } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(pageRect, box), page, null);
            } else {
                sap.setVisibleSignature(positionLoc);
                useSignatureField = true;
            }
        }

        // close the stamp, applying the changes to the PDF
        stamp.close();
        reader.close();
        cos.close();

        //delete the temp file
        file.delete();

        // apply the "signed" aspect
        serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED,
                new HashMap<QName, Serializable>());

        // create a "signature" node and associate it with the signed doc
        addSignatureNodeAssociation(actionedUponNodeRef, location, reason,
                useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc);

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.sinekartads.core.pdf.PDFTools.java

License:Open Source License

public static FinalizedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> sign(
        SignedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> signedSignature,
        //                                   X509Certificate certificate, 
        InputStream is, OutputStream os) throws SignatureException {
    ////      signAndMark(doc, certificate, is, os, null, null, null, null, null);
    //      signAndMark(signatureInfo, certificate, is, os, null, null, null);
    //   }//w ww .j av a2 s  .c om
    //
    //   public static void signAndMark(PDFSignatureInfo doc,
    //         X509Certificate certificate, InputStream is, OutputStream os,
    //         String tsaUrl, String tsaUser, String tsaPassword) {
    ////      signAndMark(doc, certificate, is, os, tsaUrl, tsaUser, tsaPassword, null, null);
    ////   }
    ////   
    ////   public static void signAndMark(DigitalSignatureDocument doc,
    ////         X509Certificate certificate, InputStream is, OutputStream os,
    ////         String tsaUrl, String tsaUser, String tsaPassword, Collection<CrlClient> crlList, OcspClient ocspClient) {
    try {
        PDFSignatureInfo signature = (PDFSignatureInfo) signedSignature;
        TSAClient tsaClient = null;

        TsRequestInfo tsRequest = signature.getTsRequest();
        if (tsRequest != null && StringUtils.isNotBlank(tsRequest.getTsUrl())) {
            tsaClient = new TSAClientBouncyCastle(tsRequest.getTsUrl(), tsRequest.getTsUsername(),
                    tsRequest.getTsPassword());
        }
        //         if (tsaUrl!=null) {
        //            tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPassword);
        //         }

        int estimatedSize = 0;
        CryptoStandard sigtype = CryptoStandard.CMS;

        // creo il reader del pdf
        PdfReader reader = new PdfReader(is);

        // creo lo stamper (se il pdf e' gia' firmato, controfirma,
        // altrimenti firma
        PdfStamper stamper = null;
        if (isPdfSigned(reader)) {
            if (tracer.isDebugEnabled())
                tracer.debug("document already signed, i will apply another sign");
            stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        } else {
            if (tracer.isDebugEnabled())
                tracer.debug("document never signed before, this is first");
            stamper = PdfStamper.createSignature(reader, os, '\0');
        }

        // questo e' il certificato su cui lavorare
        Certificate[] chain = signature.getRawX509Certificates();
        //         Certificate[] chain = new Certificate[1];
        //         chain[0] = certificate;

        // creo la signature apparence
        PdfSignatureAppearance sap = stamper.getSignatureAppearance();
        ExternalDigest externalDigest = new BouncyCastleDigest();

        // inizio codice copiato da MakeSignature

        //         Collection<byte[]> crlBytes = null;
        //           int i = 0;
        //           while (crlBytes == null && i < chain.length)
        //              crlBytes = MakeSignature.processCrl(chain[i++], crlList);
        if (estimatedSize == 0) {
            estimatedSize = 8192;
            //               if (crlBytes != null) {
            //                   for (byte[] element : crlBytes) {
            //                       estimatedSize += element.length + 10;
            //                   }
            //               }
            //               if (ocspClient != null)
            estimatedSize += 4192;
            //               if (tsaClient != null)
            estimatedSize += 4192;
        }
        sap.setCertificate(chain[0]);
        sap.setReason(signature.getReason());
        sap.setLocation(signature.getLocation());

        Calendar cal = Calendar.getInstance();
        cal.setTime(signature.getSigningTime());
        sap.setSignDate(cal);
        sap.getStamper().setUnicodeModDate(signature.getUnicodeModDate());
        sap.getStamper().setFileId(signature.getFileId());

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this
        sap.setCryptoDictionary(dic);

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

        String hashAlgorithm = signature.getDigestAlgorithm().getName();
        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME,
                externalDigest, false);
        InputStream data = sap.getRangeStream();
        byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
        //           byte[] ocsp = null;
        //           if (chain.length >= 2 && ocspClient != null) {
        //               ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
        //           }
        sgn.setExternalDigest(signature.getDigitalSignature(), null, "RSA");

        //           byte[] encodedSig = sgn.getEncodedPKCS7(hash, _getSignDate(doc.getSignDate()), tsaClient, ocsp, crlBytes, sigtype);
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsaClient, null, null, sigtype);

        if (estimatedSize + 2 < encodedSig.length)
            throw new IOException("Not enough space");

        ASN1EncodableVector extraDataVectorEncoding = new ASN1EncodableVector();
        // 
        extraDataVectorEncoding.add(new DERObjectIdentifier("1.2.840.114283")); // encoding attribute 
        extraDataVectorEncoding.add(new DERGeneralString("115.105.110.101.107.97.114.116.97"));

        // applico la firma al PDF
        byte[] extraDataVectorEncodingBytes = new DERSequence(new DERSequence(extraDataVectorEncoding))
                .getEncoded();

        byte[] paddedSig = new byte[estimatedSize];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        System.arraycopy(extraDataVectorEncodingBytes, 0, paddedSig, encodedSig.length,
                extraDataVectorEncodingBytes.length); // encoding attribute

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);

        // this should be already done, but ...
        // closing streams
        try {
            is.close();
        } catch (IOException e) {
            tracer.error("error on input stream", e);
        }
        try {
            os.flush();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        try {
            os.close();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        return signature.finalizeSignature();
        //      } catch (MarkFailedException e) {
        //         throw e;
    } catch (Exception e) {
        tracer.error("Unable to sign PDF.", e);
        throw new SignatureException("Unable to sign PDF.", e);
    }
}

From source file:org.sinekartads.core.pdf.PDFTools.java

License:Open Source License

public static DigestSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> calculateFingerPrint(
        ChainSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> chainSignature,
        //                                                           X509Certificate certificate, 
        InputStream is) throws SignatureException {
    //      calculateFingerPrint(doc, certificate, is, null, null, null, null, null);
    //   }/* w w w  . ja  va2 s. c o  m*/
    //   
    //   public static void calculateFingerPrint(DigitalSignatureDocument doc,
    //         X509Certificate certificate, InputStream is, Collection<CrlClient> crlList, OcspClient ocspClient, String tsaUrl, String tsaUser, String tsaPassword) {
    try {

        //         TSAClient tsaClient=null;
        //         
        //         if (tsaUrl!=null) {
        //            tsaClient = new SinekartaTSAClient(tsaUrl, tsaUser, tsaPassword);
        //         }
        //
        int estimatedSize = 0;
        CryptoStandard sigtype = CryptoStandard.CMS; // FIXME qui c'era CMS
        PDFSignatureInfo signature = (PDFSignatureInfo) chainSignature;

        // creo il reader del pdf
        PdfReader reader = new PdfReader(is);

        // creo lo stamper (se il pdf e' gia' firmato, controfirma,
        // altrimenti firma
        PdfStamper stamper = null;
        if (isPdfSigned(reader)) {
            if (tracer.isDebugEnabled())
                tracer.debug("calculating finger print for document already signed");
            stamper = PdfStamper.createSignature(reader, null, '\0', null, true);
        } else {
            if (tracer.isDebugEnabled())
                tracer.debug("calculating finger print for document never signed before");
            stamper = PdfStamper.createSignature(reader, null, '\0');
        }

        // questo e' il certificato su cui lavorare
        Certificate[] chain = signature.getRawX509Certificates();
        //         Certificate[] chain = new Certificate[1];
        //         chain[0] = certificate;

        // creo la signature apparence
        PdfSignatureAppearance sap = stamper.getSignatureAppearance();
        ExternalDigest externalDigest = new BouncyCastleDigest();

        // inizio codice copiato da MakeSignature

        //         Collection<byte[]> crlBytes = null;
        //           int i = 0;
        //           while (crlBytes == null && i < chain.length)
        //              crlBytes = MakeSignature.processCrl(chain[i++], crlList);
        if (estimatedSize == 0) {
            estimatedSize = 8192;
            //               if (crlBytes != null) {
            //                   for (byte[] element : crlBytes) {
            //                       estimatedSize += element.length + 10;
            //                   }
            //               }
            //               if (ocspClient != null)
            estimatedSize += 4192;
            //               if (tsaClient != null)
            estimatedSize += 4192;
        }
        Calendar now = Calendar.getInstance();
        PdfDate date = new PdfDate(now);

        sap.setSignDate(now);
        signature.setSigningTime(now.getTime());
        signature.setUnicodeModDate(date.toUnicodeString());

        sap.setCertificate(chain[0]);
        sap.setReason(signature.getReason());
        sap.setLocation(signature.getLocation());

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(date); // time-stamp will over-rule this
        sap.setCryptoDictionary(dic);

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

        String hashAlgorithm = signature.getDigestAlgorithm().getName();
        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME,
                externalDigest, false);
        //           String hashAlgorithm = Constants.SHA256;
        //           PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, Constants.BC, externalDigest, false);
        InputStream data = sap.getRangeStream();
        byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
        //           byte[] ocsp = null;
        //           if (chain.length >= 2 && ocspClient != null) {
        //               ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
        //           }
        //           byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, ocsp, crlBytes, sigtype);
        byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, null, null, sigtype);

        // calcolo dell'impronta
        MessageDigest digester = MessageDigest.getInstance(signature.getDigestAlgorithm().getName());
        byte[] fingerPrint = digester.digest(authenticatedAttributeBytes);

        //           byte[] fingerPrint = Util.digest256(authenticatedAttributeBytes);

        signature.setAuthenticatedAttributeBytes(authenticatedAttributeBytes);
        signature.setFileId(sap.getStamper().getFileId());
        //           signature.setFileIDByteContent(TextUtil.byteToHex(sap.getStamper().getFileID().getBytes()));
        signature.setUnicodeModDate(sap.getStamper().getUnicodeModDate());
        //         signature.setModDateUnicodeString(sap.getStamper().getModDate().toUnicodeString());
        signature.setSigningTime(now.getTime());
        //         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ");
        //         signature.setSignDate(sdf.format(now.getTime()));

        // this should be already done, but ...
        // closing streams
        try {
            is.close();
        } catch (IOException e) {
            tracer.error("error on input stream", e);
        }

        return signature.toDigestSignature(DigestInfo.getInstance(signature.getDigestAlgorithm(), fingerPrint));
    } catch (Exception e) {
        tracer.error("Unable to calculate finger print of PDF.", e);
        //         throw new PDFException("Unable calculate finger print of PDF.", e);
        throw new SignatureException("Unable calculate finger print of PDF.", e);
    }
}