Example usage for com.lowagie.text.pdf PdfName SUBFILTER

List of usage examples for com.lowagie.text.pdf PdfName SUBFILTER

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfName SUBFILTER.

Prototype

PdfName SUBFILTER

To view the source code for com.lowagie.text.pdf PdfName SUBFILTER.

Click Source Link

Document

A name

Usage

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void main(String[] args) throws Exception {
    byte[] pdf;//  w  w w  . j  a va  2 s.co  m
    {
        File f = new File("c:/trabalhos/java/teste.pdf");
        FileInputStream fin = new FileInputStream(f);
        pdf = new byte[(int) f.length()];
        fin.read(pdf);
        fin.close();
    }

    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 256000;

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

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.setSignDate(Calendar.getInstance());
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    byte[] signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception {
    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 128000;

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

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);/*from   w  ww  .  j a  v a2  s  . c om*/
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static byte[] getHasheableRangeFromPDF(byte[] pdf) throws Exception {
    PdfReader reader = new PdfReader(pdf);
    OutputStream fout = new NullOutputStream();

    final int SIZE = 128000;

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

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);//from   w  ww  .  java2s  .co  m
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());

    byte[] outc = new byte[(SIZE - 2) / 2];
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
    System.out.println("Hash: " + MessageDigest.getInstance("MD5").digest(data, 0, data.length));
    return data;
}

From source file:eu.europa.ec.markt.dss.validation.pades.PAdESSignature.java

License:Open Source License

@Override
public boolean checkIntegrity(Document document) {
    try {/*from ww w.  ja v a2 s .c o m*/
        if (signatureDictionary.get(PdfName.SUBFILTER) != null
                && new PdfName("ETSI.RFC3161").equals(signatureDictionary.get(PdfName.SUBFILTER))) {
            return pk.verify();
        } else {
            return pk.verify();
        }
    } catch (SignatureException e) {
        LOG.log(Level.WARNING, "Coulnd not check integrity", e);
        return false;
    }
}

From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java

License:Open Source License

@Override
protected SignatureLevelBES verifyLevelBES(AdvancedSignature signature, Date referenceTime,
        ValidationContext ctx) {/*  www  .j a  v  a 2s . co  m*/
    SignatureLevelBES superchecks = super.verifyLevelBES(signature, referenceTime, ctx);
    PAdESSignature pades = (PAdESSignature) signature;

    PdfName subfilter = pades.getSignatureDictionary().getAsName(PdfName.SUBFILTER);

    if (subfilter == null || (!subfilter.equals(new PdfName("ETSI.CAdES.detached"))
            && !subfilter.equals(new PdfName("ETSI.RFC3161")))) {
        LOG.warning(
                "Invalid or missing SubFilter value in the signature dictionary; should be either ETSI.CAdES.detached or ETSI.RFC3161");
    }

    return superchecks;
}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * Allow you to sign a PDF File with a PKCS11 session opened.
 * //from   w  ww . ja v a 2 s.  c o  m
 * @param mySign
 * @param session
 * @param pdfFiles
 * @param suffix
 * @param reason
 * @param signatureVisibility
 * @param cal
 * @throws OpenSignatureException
 * @throws TokenException
 * @throws IOException
 * @throws CertificateException
 * @throws OpenSignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws FileNotFoundException
 * @throws DocumentException
 * @throws NoSuchAlgorithmException
 * @throws ExceptionConverter
 */
public void signPDFwithKS(KeyStore ks, String alias, String pwd, File[] pdfFiles, String suffix, String reason,
        boolean signatureVisibility, Calendar cal)
        throws OpenSignatureException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {

    if (pdfFiles == null || ks == null) {
        throw new OpenSignatureException("Invalid parameters.");
    }

    // -- System's date by default 
    if (cal == null) {
        cal = Calendar.getInstance();
    }

    logger.info("[signPDFwithKS.in]:: " + Arrays.asList(new Object[] { "<ks>", alias, Arrays.asList(pdfFiles),
            suffix, reason, Boolean.valueOf(signatureVisibility) }));

    if (alias == null) {

        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alTmp = (String) aliases.nextElement();
            logger.debug("[signPDFwithKS]:: alTmp: " + alTmp);

            X509Certificate x509certificate = (X509Certificate) ks.getCertificate(alTmp);
            boolean[] keyUsage = x509certificate.getKeyUsage();
            if (keyUsage != null && (keyUsage[1] || keyUsage[0])) {
                alias = alTmp;
                break;
            }

        }
    }

    logger.debug("\n\n[signPDFwithKS]:: alias: " + alias + "\n\n");
    PrivateKey key = (PrivateKey) ks.getKey(alias, pwd.toCharArray());
    Certificate[] certs = ks.getCertificateChain(alias);

    for (int i = 0; i < pdfFiles.length; i++) {

        logger.info("[signPDFwithKS]:: Signing the file: " + pdfFiles[i].getAbsolutePath());

        try {

            // -- Check the access to the PDF
            if (!pdfFiles[i].exists() || !pdfFiles[i].canRead()) {
                throw new FileNotFoundException(
                        "The file '" + pdfFiles[i].getAbsolutePath() + "' doesn't exist.");
            }

            byte signatureBytes[] = new byte[128];

            // -- Creating the OutputStream overwritting the file if it exists
            // previously
            File fOut = FileUtils.addSuffix(pdfFiles[i], suffix, true);
            FileOutputStream fos = new FileOutputStream(fOut);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            // -- Creating the reader
            PdfReader reader = createPDFReader(pdfFiles[i]);

            PdfStamperOSP stamper;

            if ("countersigner".equals(typeSignatureSelected)) {
                stamper = PdfStamperOSP.createSignature(reader, bos, '\0', null, true);
            } else {
                stamper = PdfStamperOSP.createSignature(reader, bos, '\0');
            }

            PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance();
            sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED);
            sap.setReason(reason);

            if (signatureVisibility) {
                if ("countersigner".equals(typeSignatureSelected)) {
                    sap.setCertified(0);
                    sap.setVisibleSignature(fieldName);
                } else {
                    sap.setCertified(2);
                    if (!"".equals(fieldName)) {
                        sap.setVisibleSignature(fieldName);
                    } else {
                        sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null);
                    }
                }

            }

            sap.setExternalDigest(new byte[128], new byte[20], "RSA");

            PdfDictionary dic = new PdfDictionary();
            dic.put(PdfName.FT, PdfName.SIG);
            dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite"));
            dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));
            if (cal != null) {
                dic.put(PdfName.M, new PdfDate(cal));
            } else {
                dic.put(PdfName.M, new PdfNull());
            }
            dic.put(PdfName.NAME,
                    new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN")));
            dic.put(PdfName.REASON, new PdfString(reason));

            sap.setCryptoDictionary(dic);

            HashMap exc = new HashMap();
            exc.put(PdfName.CONTENTS, new Integer(0x5002));
            sap.preClose(exc);

            byte[] content = IOUtils.streamToByteArray(sap.getRangeStream());
            //SHA256, alias CMSSignedDataGenerator.DIGEST_SHA256,
            //        alias NISTObjectIdentifiers.id_sha256.getId(),
            //        alias "2.16.840.1.101.3.4.2.1"
            byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content);

            // costruzione degli authenticated attributes
            ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal);
            byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes));

            // -- Signature generated with the private key of the KS
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(key);
            signature.update(bytesForSecondHash);
            signatureBytes = signature.sign();

            byte[] encodedPkcs7 = null;
            try {

                // Create the set of Hash algorithms
                DERConstructedSet digestAlgorithms = new DERConstructedSet();

                // Creo manualmente la sequenza di digest algos
                ASN1EncodableVector algos = new ASN1EncodableVector();
                //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
                //SHA-256
                algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
                algos.add(new DERNull());
                digestAlgorithms.addObject(new DERSequence(algos));

                // Create the contentInfo.
                ASN1EncodableVector ev = new ASN1EncodableVector();
                ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData

                DERSequence contentinfo = new DERSequence(ev);

                // Get all the certificates
                //
                ASN1EncodableVector v = new ASN1EncodableVector();
                for (int c = 0; c < certs.length; c++) {
                    ASN1InputStream tempstream = new ASN1InputStream(
                            new ByteArrayInputStream(certs[c].getEncoded()));
                    v.add(tempstream.readObject());
                }

                DERSet dercertificates = new DERSet(v);

                // Create signerinfo structure.
                //
                ASN1EncodableVector signerinfo = new ASN1EncodableVector();

                // Add the signerInfo version
                //
                signerinfo.add(new DERInteger(1));

                v = new ASN1EncodableVector();
                v.add(CertUtil.getIssuer((X509Certificate) certs[0]));
                v.add(new DERInteger(((X509Certificate) certs[0]).getSerialNumber()));
                signerinfo.add(new DERSequence(v));

                // Add the digestAlgorithm
                v = new ASN1EncodableVector();
                //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
                //SHA-256
                v.add(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
                v.add(new DERNull());
                signerinfo.add(new DERSequence(v));

                // add the authenticated attribute if present
                signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes)));

                // Add the digestEncryptionAlgorithm
                v = new ASN1EncodableVector();
                v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA
                v.add(new DERNull());
                signerinfo.add(new DERSequence(v));

                // Add the encrypted digest
                signerinfo.add(new DEROctetString(signatureBytes));

                // Add unsigned attributes (timestamp)
                if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) {
                    byte[] timestampHash = MessageDigest.getInstance("SHA-256").digest(signatureBytes);
                    ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash,
                            serverTimestamp, usernameTimestamp, passwordTimestamp);
                    if (unsignedAttributes != null) {
                        signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes)));
                    }
                }

                // Finally build the body out of all the components above
                ASN1EncodableVector body = new ASN1EncodableVector();
                body.add(new DERInteger(1)); // pkcs7 version, always 1
                body.add(digestAlgorithms);
                body.add(contentinfo);
                body.add(new DERTaggedObject(false, 0, dercertificates));

                // Only allow one signerInfo
                body.add(new DERSet(new DERSequence(signerinfo)));

                // Now we have the body, wrap it in it's PKCS7Signed shell
                // and return it
                //
                ASN1EncodableVector whole = new ASN1EncodableVector();
                whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA
                whole.add(new DERTaggedObject(0, new DERSequence(body)));

                encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole));

            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }

            PdfDictionary dic2 = new PdfDictionary();

            byte out[] = new byte[0x5000 / 2];
            System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length);

            dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true));
            sap.close(dic2);

            bos.close();
            fos.close();

        } catch (Exception e) {
            logger.warn("[signPDFwithKS]:: ", e);
        }

    }

    logger.info("[signPDFwithKS.out]:: ");

}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * @param mySign//from ww w  .j  a va2s  .c o  m
 * @param session
 * @param reason
 * @param signCertKeyObject
 * @param certs
 * @param stamper
 * @throws IOException
 * @throws DocumentException
 * @throws NoSuchAlgorithmException
 * @throws TokenException
 * @throws ExceptionConverter
* @throws NoSuchProviderException 
 */
private void createSignatureAppearance(MyPkcs11 mySign, Session session, String reason, Key signCertKeyObject,
        X509Certificate[] certs, PdfStamperOSP stamper, boolean signatureVisible, Calendar cal)
        throws IOException, DocumentException, NoSuchAlgorithmException, TokenException, ExceptionConverter,
        NoSuchProviderException {

    logger.info("[createSignatureAppearance.in]:: ");

    byte[] signatureBytes = new byte[128];

    PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance();

    sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED);
    sap.setReason(reason);

    if (signatureVisible) {
        if ("countersigner".equals(typeSignatureSelected)) {
            sap.setCertified(0);
            sap.setVisibleSignature(fieldName);
        } else {
            sap.setCertified(0);
            if ((fieldName != null) && (!"".equals(fieldName))) {
                sap.setVisibleSignature(fieldName);
            } else {
                sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null);
            }
        }

    }

    //aggiunta di grafico per la firma
    if ("true".equals(graphicSignSelected)) {
        sap.setSignatureGraphic(Image.getInstance(fileImgfirma));
        sap.setRender(2);
    } else {
        sap.setRender(0);
    }
    sap.setExternalDigest(new byte[128], new byte[20], "RSA");

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.FT, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));
    if (cal != null) {
        dic.put(PdfName.M, new PdfDate(cal));
    } else {
        dic.put(PdfName.M, new PdfNull());
    }
    dic.put(PdfName.NAME, new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN")));
    dic.put(PdfName.REASON, new PdfString(reason));

    sap.setCryptoDictionary(dic);

    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(0x5002));
    sap.preClose(exc);

    byte[] content = IOUtils.streamToByteArray(sap.getRangeStream());
    byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content);

    // costruzione degli authenticated attributes
    ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal);
    byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes));

    byte[] secondHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1").digest(bytesForSecondHash);

    // -- Generatting the signature
    signatureBytes = mySign.sign(session, secondHash, signCertKeyObject);

    byte[] encodedPkcs7 = null;
    try {

        // Create the set of Hash algorithms
        DERConstructedSet digestAlgorithms = new DERConstructedSet();

        // Creo manualmente la sequenza di digest algos
        ASN1EncodableVector algos = new ASN1EncodableVector();
        //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA256
        algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        algos.add(new DERNull());
        digestAlgorithms.addObject(new DERSequence(algos));

        // Create the contentInfo.
        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData

        DERSequence contentinfo = new DERSequence(ev);

        // Get all the certificates
        //
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (int c = 0; c < certs.length; c++) {
            ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(certs[c].getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new DERInteger(1));

        v = new ASN1EncodableVector();
        v.add(CertUtil.getIssuer(certs[0]));
        v.add(new DERInteger(certs[0].getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA-256
        v.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes)));

        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the encrypted digest
        signerinfo.add(new DEROctetString(signatureBytes));

        // Add unsigned attributes (timestamp)
        if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) {
            byte[] timestampHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC")
                    .digest(signatureBytes);
            ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash, serverTimestamp,
                    usernameTimestamp, passwordTimestamp);
            if (unsignedAttributes != null) {
                signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes)));
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(1)); // pkcs7 version, always 1
        body.add(digestAlgorithms);
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole));

    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }

    PdfDictionary dic2 = new PdfDictionary();

    byte out[] = new byte[0x5000 / 2];
    System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length);

    dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true));
    sap.close(dic2);

    logger.info("[createSignatureAppearance.retorna]:: ");

}