Example usage for com.itextpdf.text.pdf PdfSignatureAppearance setCertificate

List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setCertificate

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfSignatureAppearance setCertificate.

Prototype

public void setCertificate(Certificate signCertificate) 

Source Link

Document

Sets the certificate used to provide the text in the appearance.

Usage

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;//from  w w  w  . j  a  v  a 2s.c  om

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:org.opencps.pki.PdfSigner.java

License:Open Source License

/**
 * Compute digest hash//from ww  w. ja  v a2  s.  c  o m
 */
protected byte[] computeDigest(float llx, float lly, float urx, float ury) throws SignatureException {
    byte digestHash[] = null;
    int contentEstimated = 8192;
    try {
        PdfReader reader = new PdfReader(getOriginFilePath());
        FileOutputStream os = new FileOutputStream(getTempFilePath());
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        signatureFieldName = appearance.getNewSigName();
        TSAClient tsaClient = null;
        appearance.setCertificate(getCertificate());
        String tsaUrl = CertificateUtil.getTSAURL(getCertificate());
        if (tsaUrl != null) {
            tsaClient = new TSAClientBouncyCastle(tsaUrl);
        }
        if (tsaClient != null) {
            LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName);
            contentEstimated += 4096;
        }

        appearance.setSignDate(signDate);
        CertificateInfo certInfo = new CertificateInfo(getCertificate());
        appearance.setLocation(certInfo.getOrganizationUnit());
        appearance.setReason("Document is signed by " + certInfo.getCommonName());
        appearance.setContact(certInfo.getCommonName());
        if (!isVisible) {
            appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName);
        } else {
            if (signatureImage != null) {
                appearance.setSignatureGraphic(signatureImage.getImage());
                appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            } else {
                appearance.setLayer2Text(certInfo.getCommonName());
            }
            appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
        }

        ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE,
                PdfName.ADBE_PKCS7_DETACHED);
        MakeSignature.signExternalContainer(appearance, external, contentEstimated);

        digestHash = DigestAlgorithms.digest(appearance.getRangeStream(),
                digest.getMessageDigest(getHashAlgorithm().toString()));

        reader.close();
        os.close();
    } catch (Exception e) {
        throw new SignatureException(e.getMessage(), e);
    }
    return digestHash;
}

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 a  v a2 s .  c  o m*/
    //
    //   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);
    //   }//from w  w  w. ja  v a 2s. 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);
    }
}