Example usage for com.itextpdf.text.pdf.security BouncyCastleDigest BouncyCastleDigest

List of usage examples for com.itextpdf.text.pdf.security BouncyCastleDigest BouncyCastleDigest

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf.security BouncyCastleDigest BouncyCastleDigest.

Prototype

BouncyCastleDigest

Source Link

Usage

From source file:SigningProcess.java

public static String sign(String base64, HashMap map) {
    String base64string = null;//from  www .j  a v a2s . co m
    try {
        System.out.println("map :" + map);
        // Getting a set of the entries
        Set set = map.entrySet();
        System.out.println("set :" + set);
        // Get an iterator
        Iterator it = set.iterator();
        // Display elements
        while (it.hasNext()) {
            Entry me = (Entry) it.next();
            String key = (String) me.getKey();
            if ("privateKey".equalsIgnoreCase(key)) {
                privateKey = (PrivateKey) me.getValue();
            }
            if ("certificateChain".equalsIgnoreCase(key)) {
                certificateChain = (X509Certificate[]) me.getValue();
            }
        }

        OcspClient ocspClient = new OcspClientBouncyCastle();
        TSAClient tsaClient = null;
        for (int i = 0; i < certificateChain.length; i++) {
            X509Certificate cert = (X509Certificate) certificateChain[i];
            String tsaUrl = CertificateUtil.getTSAURL(cert);
            if (tsaUrl != null) {
                tsaClient = new TSAClientBouncyCastle(tsaUrl);
                break;
            }
        }
        List<CrlClient> crlList = new ArrayList<CrlClient>();
        crlList.add(new CrlClientOnline(certificateChain));

        String property = System.getProperty("java.io.tmpdir");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] FileByte = decoder.decodeBuffer(base64);
        writeByteArraysToFile(property + "_unsigned.pdf", FileByte);

        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(property + "_unsigned.pdf");
        FileOutputStream os = new FileOutputStream(property + "_signed.pdf");
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        //            appearance.setReason(reason);
        //            appearance.setLocation(location);
        appearance.setAcro6Layers(false);
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig1");
        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature((PrivateKey) privateKey, DigestAlgorithms.SHA256,
                providerMSCAPI.getName());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, pks, certificateChain, crlList, ocspClient, tsaClient, 0,
                MakeSignature.CryptoStandard.CMS);

        InputStream docStream = new FileInputStream(property + "_signed.pdf");
        byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(docStream));
        base64string = new String(encodeBase64);
    } catch (IOException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (DocumentException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (GeneralSecurityException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    }
    return base64string;
}

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

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

    try {//from   w  w w.  j  a v a 2 s . c om
        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  w w .  ja  v a  2 s. com
        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.vectorprint.report.itext.style.stylers.DocumentSettings.java

License:Open Source License

/**
 * adds a visible signature of 200 / 100 at top left of the first page of the pdf with "verify origin" as reason, the
 * localhost name as location. Uses MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0,
 * MakeSignature.CryptoStandard.CMS)//  w w  w  . j a  va  2s . c om
 *
 * @see #loadKeyStore(char[])
 * @see #getKey(java.security.KeyStore, java.lang.String, char[]) }
 * @param psa
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws VectorPrintException
 */
@Override
public void configureVisualSignature(PdfSignatureAppearance psa)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, VectorPrintException {
    psa.setReason("verify origin");
    try {
        psa.setLocation(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException ex) {
        log.log(Level.WARNING, "unable to set location for pdf signature", ex);
    }

    char[] pw = getValue(KEYSTORE_PASSWORD, char[].class);
    char[] clone = pw.clone();
    KeyStore ks = loadKeyStore(pw);

    PrivateKey key = getKey(ks, (String) ks.aliases().nextElement(), clone);
    Certificate[] certificateChain = ks.getCertificateChain((String) ks.aliases().nextElement());

    PrivateKeySignature pks = new PrivateKeySignature(key, getValue(DIGESTPARAM, DIGESTALGORITHM.class).name(),
            "BC");
    ExternalDigest as = new BouncyCastleDigest();

    psa.setVisibleSignature(new Rectangle(0, getHeight() - 100, 200, getHeight()), 1, "signature");
    try {
        MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0,
                MakeSignature.CryptoStandard.CMS);
    } catch (IOException | DocumentException | GeneralSecurityException ex) {
        throw new VectorPrintException(ex);
    }
}

From source file:de.sign.SignMain.java

License:Open Source License

public void sign() throws DocumentException, IOException, GeneralSecurityException {

    PdfReader reader = new PdfReader(this.orgFile);
    OutputStream os = new FileOutputStream(this.orgFile.replace(".pdf", "SIGN.pdf"));
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');

    // Create appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    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);
    appearance.setVisibleSignature(rectangle, 1, "sig");
    appearance.setLocation(getHostname());
    appearance.setReason("Evidence of document integrity");
    appearance.setCertificationLevel(1); // 1 = CERTIFIED_NO_CHANGES_ALLOWED
    appearance.setAcro6Layers(false);//from w w w.j a v  a2 s . co m
    appearance.setLayer2Text("");

    //Sign
    Security.addProvider(new BouncyCastleProvider());
    TSAClient tsc = new TSAClientBouncyCastle(this.tsa_URL);
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(getPrivateKey(), "SHA-1", "BC");
    MakeSignature.signDetached(appearance, digest, signature, getCertificateChain(), null, null, tsc, 0,
            CryptoStandard.CMS);
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertSignature(String src, String dest, String Keystore, String name, String password,
        int masterHeight, int masterWidth, int pageNum)
        throws GeneralSecurityException, IOException, DocumentException {

    float[] scalar = scale(1, 1, 120, 32, masterHeight, masterWidth, pageNum);
    float[] trans = translate(1, 1, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight,
            masterWidth, pageNum);/*from   w w w .j  a  va2 s .  co m*/
    float[] f = commentTrans(1, 1, masterHeight, masterWidth, pageNum);

    float shift = 0;

    float pageChunk = r[pageNum - 1].getHeight() / 10;
    shift = r[pageNum - 1].getHeight() / 100;
    scalar[1] = (int) (pageChunk);
    scalar[0] = (int) (120 * pageChunk) / 32;
    trans[0] = (int) (0 + (pageChunk * widthScalar));
    trans[1] = (int) (r[pageNum - 1].getHeight() - (pageChunk * heightScalar) - (shift * (heightScalar + 2)));
    heightScalar = heightScalar + 1;
    if (heightScalar == 8) {
        heightScalar = 0;
        widthScalar = widthScalar + 2;
    }

    /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    trans = translateRotation(trans[0], trans[1], pageNum);

    Rectangle cropBox = pds.getReader().getCropBox(1);
    Rectangle rectangle = new Rectangle(trans[0] + shift, trans[1] - scalar[1], trans[0] + shift + 120,
            trans[1] - scalar[1] + 32);
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(Keystore), password.toCharArray());
    String alias = (String) ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setVisibleSignature(rectangle, 1, name);
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);

    return "";
}

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

License:Open Source License

/**
 * Constructor/*from   w w  w  .j av  a 2  s  .com*/
 *
 * @param filePath The path of pdf document
 * @param cert The certificate of user
 * @param tempFilePath Temporary Pdf document file path after generate hash key
 * @param signedFilePath Signed Pdf document file path
 * @param isVisible Signature is visible
 */
public PdfSigner(String filePath, X509Certificate cert, String tempFilePath, String signedFilePath,
        boolean isVisible) {
    super(filePath, cert, tempFilePath, signedFilePath);
    this.isVisible = isVisible;
    signDate = Calendar.getInstance();
    digest = new BouncyCastleDigest();
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    IOUtils.closeQuietly(is);/*from w  w w.  jav a  2 s .  co m*/

    PdfReader reader = new PdfReader(input.toString());
    FileOutputStream os = new FileOutputStream(signedPDF.toFile());
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setContact(contact);
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
    MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
    IOUtils.closeQuietly(os);
    reader.close();

    return signedPDF;
}

From source file:org.roda.core.plugins.plugins.characterization.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream is = new FileInputStream(keystore)) {
        ks.load(is, password.toCharArray());

        PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        try (FileOutputStream os = new FileOutputStream(signedPDF.toFile())) {
            PdfReader reader = new PdfReader(input.toString());
            PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            appearance.setReason(reason);
            appearance.setLocation(location);
            appearance.setContact(contact);
            appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
            ExternalDigest digest = new BouncyCastleDigest();
            ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
            MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
            reader.close();//from w w  w.  j  a  va  2s . c  om
        }
    }

    return signedPDF;
}

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);
    //   }/*from w w  w  . j  ava  2 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);
    }
}