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

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

Introduction

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

Prototype

PdfName TYPE

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

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.ja  v  a 2s. c  o 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);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);//from   ww w . jav  a 2s. co m
    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);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);//from  w ww.j av a2 s  . com
    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.cedefop.europass.jtool.util.ExtractAttachments.java

License:EUPL

/**
* Get the attachment file     /*w  w  w .  j  a  v  a2s. c  o  m*/
* @param filespec 
* @throws IOException
*/
public void unpackFile(PdfDictionary filespec) throws IOException {
    if (filespec == null)
        return;

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type))
        return;

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null)
        return;

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null)
        return;

    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null)
        return;
    byte b[] = PdfReader.getStreamBytes(prs);
    FileOutputStream fout = new FileOutputStream(trgfile);
    fout.write(b);
    fout.close();
}

From source file:eu.europa.ec.markt.dss.signature.pdf.itext.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters)
        throws IOException {

    try {//from www . j  a  va2s.c om
        PdfReader reader = new PdfReader(pdfData);
        PdfStamper stamper = PdfStamper.createSignature(reader, output, '\0', null, true);

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setAcro6Layers(true);
        appearance.setRender(PdfSignatureAppearance.SignatureRenderDescription);

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.RFC3161"));
        // defined in ETSI TS 102 778-4 A.2
        dic.put(PdfName.TYPE, new PdfName("DocTimeStamp"));

        Calendar cal = Calendar.getInstance();
        if (parameters.getSigningDate() != null) {
            cal.setTime(parameters.getSigningDate());
            appearance.setSignDate(cal);
        }
        dic.setDate(new PdfDate(cal));

        appearance.setCryptoDictionary(dic);

        int csize = getSignatureSize();
        HashMap exc = new HashMap();
        exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2));

        appearance.preClose(exc);

        return stamper;
    } catch (DocumentException e) {
        throw new IOException(e);
    }

}

From source file:eu.europa.ec.markt.dss.signature.pdf.ITextPDFDocTimeSampService.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters)
        throws IOException, DocumentException {

    PdfReader reader = new PdfReader(pdfData);
    PdfStamper stp = PdfStamper.createSignature(reader, output, '\0', null, true);

    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setAcro6Layers(true);/*from  w w  w . j  a v  a2 s  .  c o m*/
    sap.setRender(PdfSignatureAppearance.SignatureRenderDescription);

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.RFC3161"));
    // defined in ETSI TS 102 778-4 A.2
    dic.put(PdfName.TYPE, new PdfName("DocTimeStamp"));

    Calendar cal = Calendar.getInstance();
    if (parameters.getSigningDate() != null) {
        cal.setTime(parameters.getSigningDate());
        sap.setSignDate(cal);
    }
    dic.setDate(new PdfDate(cal));

    sap.setCryptoDictionary(dic);

    int csize = getSignatureSize();
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2));

    sap.preClose(exc);

    return stp;
}

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

License:Open Source License

@Override
protected SignatureLevelLTV verifyLevelLTV(AdvancedSignature signature, Date referenceTime,
        ValidationContext ctx) {/*from  w  w w .j  a  va2s  . c  o m*/
    try {
        PAdESSignature pades = (PAdESSignature) signature;
        LOG.info("Starting LTV validation of signature: " + pades.getPdfPkcs7().getSignName() + " / "
                + PdfPKCS7.getSubjectFields(pades.getPdfPkcs7().getSigningCertificate()));

        PdfDictionary catalog = pades.getOuterCatalog();
        if (catalog == null) {
            catalog = pades.getPdfReader().getCatalog();
        }

        PdfDictionary dss = catalog.getAsDict(new PdfName("DSS"));

        if (dss == null) {
            LOG.info("No DSS dictionary!");
            return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.dss.dictionary"), null, null);
        }

        LOG.info("DSS dictionary found");

        PdfName sigType = pades.getSignatureDictionary().getAsName(PdfName.TYPE);
        // PdfName subfilter = pades.getSignatureDictionary().getAsName(PdfName.SUBFILTER);

        TimestampVerificationResult docTimestampCheck = null;

        boolean dssCertsVerificationResult = everyCertificateValueAreThere(ctx,
                pades.getExtendedCertificateSource().getCertificates(), pades.getSigningCertificate());
        boolean dssRevocationVerificationResult = true;
        dssRevocationVerificationResult &= everyCRLValueOrRefAreThere(ctx, pades.getCRLs());
        dssRevocationVerificationResult &= everyOCSPValueOrRefAreThere(ctx, pades.getOCSPs());
        boolean vriVerificationresult = true;

        if (sigType != null) {
            if (sigType.equals(new PdfName("Sig"))) {
                // Standard signature

                PdfDictionary vri = dss.getAsDict(new PdfName("VRI"));

                if (vri == null) {
                    LOG.info("No VRI dictionary, this is optional but required by Adobe Acrobat");
                    return new SignatureLevelLTV(new Result(ResultStatus.INVALID, "no.vri.dictionary"), null,
                            null);
                }

                // Verify the VRI
                MessageDigest _md = MessageDigest.getInstance("SHA1");
                String hexHash = Hex
                        .encodeHexString(
                                _md.digest(pades.getSignatureDictionary().get(PdfName.CONTENTS).getBytes()))
                        .toUpperCase();

            } else if (sigType.equals(new PdfName("DocTimeStamp"))) {

            } else {
                throw new RuntimeException("Unknown signature dictionary type");
            }
        }

        Result levelReached = null;
        if (dssCertsVerificationResult && dssRevocationVerificationResult) {
            levelReached = new Result(ResultStatus.VALID, null);
        } else {
            levelReached = new Result();
            if (!dssCertsVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.certs.verification.result.error");
            } else if (!dssRevocationVerificationResult) {
                levelReached.setStatus(ResultStatus.INVALID, "dss.revocation.verification.result.error");
            } else if (!vriVerificationresult) {
                levelReached.setStatus(ResultStatus.INVALID, "vri.verification.result.error");
            }
        }

        return new SignatureLevelLTV(levelReached,
                new Result((dssCertsVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID, null),
                new Result((dssRevocationVerificationResult) ? ResultStatus.VALID : ResultStatus.INVALID,
                        null));

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java

License:Open Source License

private static int getNumber(PdfIndirectReference indirect) {
    PdfDictionary pdfObj = (PdfDictionary) PdfReader.getPdfObjectRelease(indirect);
    if (pdfObj.contains(PdfName.TYPE) && pdfObj.get(PdfName.TYPE).equals(PdfName.PAGES)
            && pdfObj.contains(PdfName.KIDS)) {
        PdfArray kids = (PdfArray) pdfObj.get(PdfName.KIDS);
        indirect = (PdfIndirectReference) kids.getPdfObject(0);
    }/*  w  w w .ja v  a2  s  .c o  m*/
    return indirect.getNumber();
}

From source file:net.sqs2.omr.master.sqm.PDFAttachmentExtractor.java

License:Apache License

/**
 * Unpacks a file attachment.//from  www . j a  v a2s.  com
 * 
 * @param reader
 *            The object that reads the PDF document
 * @param filespec
 *            The dictionary containing the file specifications
 * @param outPath
 *            The path where the attachment has to be written
 * @throws IOException
 */
private static byte[] unpackFile(PdfReader reader, PdfDictionary filespec, String suffix) throws IOException {
    if (filespec == null) {
        return null;
    }
    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
        return null;
    }
    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null) {
        return null;
    }
    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null) {
        return null;
    }
    File fLast = new File(fn.toUnicodeString());
    String filename = fLast.getName();

    if (!filename.endsWith(suffix)) {
        return null;
    }

    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null) {
        return null;
    }
    return PdfReader.getStreamBytes(prs);
}

From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java

License:Open Source License

/**
 * Unpacks a file attachment.//from ww w  .j  ava  2s .c  o m
 * @param reader The object that reads the PDF document
 * @param filespec The dictonary containing the file specifications
 * @throws IOException
 */

protected static Object[] unpackFile(PdfReader reader, PdfDictionary filespec) throws IOException {
    Object arr[] = new Object[2]; //use to store name and file bytes
    if (filespec == null) {
        return null;
    }

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
        return null;
    }

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null) {
        return null;
    }

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null) {
        return null;
    }

    File fLast = new File(fn.toUnicodeString());
    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null) {
        return null;
    }

    byte attachmentByte[] = PdfReader.getStreamBytes(prs);
    arr[0] = fLast.getName();
    arr[1] = attachmentByte;

    return arr;

}