public String hashSignExternalTimestamp(String read, String write) throws Exception {
    Provider prov = entry.getProvider();
    PrivateKey key = entry.getPrivateKey();
    Certificate[] chain = entry.getCertificateChain();

    PdfReader reader = new PdfReader(read);
    int pageCount = reader.getNumberOfPages();

    File outputFile = new File(write);
    PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true);

    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setProvider(prov.getName());
    sap.setReason(getReason());
    sap.setLocation(getLocation());
    sap.setContact(getContact());

    sap.setCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);

    int[] coord = LoadImageAction.getImageXY();

    if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample
      coord[0] = LoadImageAction.getAssX();
      coord[1] = LoadImageAction.getAssY();
    }

    // Adicionar imagem ao PDF se for para utilizar
    if (!isSignatureVisible()) {
      sap.setLayer2Text("");
    } else {
      if (LoadImageAction.getFlagPDF()) {
        sap.setAcro6Layers(true);
        Image img = LoadImageAction.getAssImagePDF();

        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              pageCount,
              null);
        else
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text("\n\n(Doc. assinado digitalmente)");
        sap.setImage(img);
      } else {
        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40), pageCount, null);
        else
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text(getSignatureText((X509Certificate) chain[0], sap.getSignDate()));
      }
    }

    PdfSignature dic =
        new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$
    dic.setReason(sap.getReason());
    dic.setLocation(sap.getLocation());
    dic.setContact(sap.getContact());
    dic.setDate(new PdfDate(sap.getSignDate()));
    sap.setCryptoDictionary(dic);
    int contentEstimated = 15000;
    HashMap<Object, Object> exc = new HashMap<Object, Object>();
    exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    sap.preClose(exc);

    PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false);
    InputStream data = sap.getRangeStream();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
    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();
    byte[] ocsp = null;
    if (isUseOCSP() && chain.length >= 2) {
      String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
      if (url != null && url.length() > 0)
        ocsp =
            new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url)
                .getEncoded();
    }
    byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
    sgn.update(sh, 0, sh.length);
    TSAClient tsc = null;
    if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation);

    // o PIN/PASS dos certificados � pedido aqui
    byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

    if (contentEstimated + 2 < encodedSig.length)
      throw new Exception("Not enough space"); // $NON-NLS-1$

    byte[] paddedSig = new byte[contentEstimated];
    System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    sap.close(dic2);

    deleteFile(read);
    return write;
  }