Example usage for org.apache.pdfbox.cos COSName V

List of usage examples for org.apache.pdfbox.cos COSName V

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSName V.

Prototype

COSName V

To view the source code for org.apache.pdfbox.cos COSName V.

Click Source Link

Usage

From source file:ShowSignature.java

License:Apache License

private void showSignature(String[] args) throws IOException, CertificateException {
    if (args.length != 2) {
        usage();/*from w  w  w. j  a  va 2s  .c o  m*/
    } else {
        String password = args[0];
        String infile = args[1];
        PDDocument document = null;
        try {
            document = PDDocument.load(new File(infile), password);
            if (!document.isEncrypted()) {
                System.err.println("Warning: Document is not encrypted.");
            }

            COSDictionary trailer = document.getDocument().getTrailer();
            COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
            COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
            COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
            for (int i = 0; i < fields.size(); i++) {
                COSDictionary field = (COSDictionary) fields.getObject(i);
                COSName type = field.getCOSName(COSName.FT);
                if (COSName.SIG.equals(type)) {
                    COSDictionary cert = (COSDictionary) field.getDictionaryObject(COSName.V);
                    if (cert != null) {
                        System.out.println("Certificate found");
                        System.out.println("Name=" + cert.getDictionaryObject(COSName.NAME));
                        System.out.println("Modified=" + cert.getDictionaryObject(COSName.M));
                        COSName subFilter = (COSName) cert.getDictionaryObject(COSName.SUB_FILTER);
                        if (subFilter != null) {
                            if (subFilter.getName().equals("adbe.x509.rsa_sha1")) {
                                COSString certString = (COSString) cert
                                        .getDictionaryObject(COSName.getPDFName("Cert"));
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else if (subFilter.getName().equals("adbe.pkcs7.sha1")) {
                                COSString certString = (COSString) cert.getDictionaryObject(COSName.CONTENTS);
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else {
                                System.err.println("Unknown certificate type:" + subFilter);
                            }
                        } else {
                            throw new IOException("Missing subfilter for cert dictionary");
                        }
                    } else {
                        System.out.println("Signature found, but no certificate");
                    }
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java

License:Apache License

/**
 * Sets value of {@link PDSignatureField}.
 * @param doc {@link PDDocument}/*from w w w  .  ja v  a  2  s . c o m*/
 * @param field {@link PDSignatureField}
 * @param signatureInputStream {@link InputStream}
 * @return {@link SignatureOptions}
 * @throws IOException IOException
 */
private SignatureOptions setValue(final PDDocument doc, final PDSignatureField field,
        final InputStream signatureInputStream) throws IOException {

    int accessPermissions = SigUtils.getMDPPermission(doc);
    if (accessPermissions == 1) {
        throw new IllegalStateException("No changes to the document are "
                + "permitted due to DocMDP transform parameters " + "dictionary");
    }

    // retrieve signature dictionary
    PDSignature signature = field.getSignature();

    if (signature == null) {
        signature = new PDSignature();
        // after solving PDFBOX-3524 - signatureField.setValue(signature)
        // until then:
        field.getCOSObject().setItem(COSName.V, signature);
    } else {
        throw new IllegalStateException(
                "The signature field " + field.getFullyQualifiedName() + " is already signed.");
    }

    // Optional: certify
    // can be done only if version is at least 1.5 and if not already set
    // doing this on a PDF/A-1b file fails validation by Adobe
    // preflight (PDFBOX-3821)
    // PDF/A-1b requires PDF version 1.4 max, so don't increase the version
    // on such files.
    final float version = 1.5f;
    if (doc.getVersion() >= version && accessPermissions == 0) {
        SigUtils.setMDPPermission(doc, signature, 2);
    }

    PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
    if (acroForm != null && acroForm.getNeedAppearances()) {
        // PDFBOX-3738 NeedAppearances true results in visible signature
        // becoming invisible
        // with Adobe Reader
        if (acroForm.getFields().isEmpty()) {
            // we can safely delete it if there are no fields
            acroForm.getCOSObject().removeItem(COSName.NEED_APPEARANCES);
            // note that if you've set MDP permissions, the removal of this
            // item
            // may result in Adobe Reader claiming that the document has
            // been changed.
            // and/or that field content won't be displayed properly.
            // ==> decide what you prefer and adjust your code accordingly.
        }
    }

    // default filter
    signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);

    // subfilter for basic and PAdES Part 2 signatures
    signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);

    PDVisibleSignDesigner visibleSignDesigner = new PDVisibleSignDesigner(signatureInputStream);

    PDVisibleSigProperties visibleSigProps = new PDVisibleSigProperties();
    visibleSigProps
            //        .signerName(name)  // TODO add..
            //        .signerLocation(location) // TODO add.
            //        .signatureReason(reason)
            //        .preferredSize(preferredSize)
            //        .page(0) // TODO fix
            .visualSignEnabled(true).setPdVisibleSignature(visibleSignDesigner);

    visibleSigProps.buildSignature();

    signature.setName(visibleSigProps.getSignerName());
    signature.setLocation(visibleSigProps.getSignerLocation());
    signature.setReason(visibleSigProps.getSignatureReason());

    // the signing date, needed for valid signature
    signature.setSignDate(Calendar.getInstance());

    SignatureOptions sigOptions = new SignatureOptions();
    sigOptions.setVisualSignature(visibleSigProps.getVisibleSignature());
    sigOptions.setPage(visibleSigProps.getPage() - 1);
    doc.addSignature(signature, this, sigOptions);

    return sigOptions;
}

From source file:com.formkiq.core.service.generator.pdfbox.SigUtils.java

License:Apache License

/**
 * Set the access permissions granted for this document in the DocMDP
 * transform parameters dictionary. Details are described in the table
 * "Entries in the DocMDP transform parameters dictionary" in the PDF
 * specification.//  w ww  . ja  va2  s  . co m
 *
 * @param doc
 *            The document.
 * @param signature
 *            The signature object.
 * @param accessPermissions
 *            The permission value (1, 2 or 3).
 */
public static void setMDPPermission(final PDDocument doc, final PDSignature signature,
        final int accessPermissions) {

    COSDictionary sigDict = signature.getCOSObject();

    // DocMDP specific stuff
    COSDictionary transformParameters = new COSDictionary();
    transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
    transformParameters.setInt(COSName.P, accessPermissions);
    transformParameters.setName(COSName.V, "1.2");
    transformParameters.setNeedToBeUpdated(true);

    COSDictionary referenceDict = new COSDictionary();
    referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
    referenceDict.setItem("TransformMethod", COSName.DOCMDP);
    referenceDict.setItem("DigestMethod", COSName.getPDFName("SHA1"));
    referenceDict.setItem("TransformParams", transformParameters);
    referenceDict.setNeedToBeUpdated(true);

    COSArray referenceArray = new COSArray();
    referenceArray.add(referenceDict);
    sigDict.setItem("Reference", referenceArray);
    referenceArray.setNeedToBeUpdated(true);

    // Catalog
    COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
    COSDictionary permsDict = new COSDictionary();
    catalogDict.setItem(COSName.PERMS, permsDict);
    permsDict.setItem(COSName.DOCMDP, signature);
    catalogDict.setNeedToBeUpdated(true);
    permsDict.setNeedToBeUpdated(true);
}

From source file:com.modemo.javase.signature.SigUtils.java

License:Apache License

/**
 * Set the access permissions granted for this document in the DocMDP transform parameters
 * dictionary. Details are described in the table "Entries in the DocMDP transform parameters
 * dictionary" in the PDF specification.
 *
 * @param doc The document./*from www.j a va 2s.  c  o m*/
 * @param signature The signature object.
 * @param accessPermissions The permission value (1, 2 or 3).
 */
static public void setMDPPermission(PDDocument doc, PDSignature signature, int accessPermissions) {
    COSDictionary sigDict = signature.getCOSObject();

    // DocMDP specific stuff
    COSDictionary transformParameters = new COSDictionary();
    transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
    transformParameters.setInt(COSName.P, accessPermissions);
    transformParameters.setName(COSName.V, "1.2");
    transformParameters.setNeedToBeUpdated(true);

    COSDictionary referenceDict = new COSDictionary();
    referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
    referenceDict.setItem("TransformMethod", COSName.DOCMDP);
    referenceDict.setItem("DigestMethod", COSName.getPDFName("SHA1"));
    referenceDict.setItem("TransformParams", transformParameters);
    referenceDict.setNeedToBeUpdated(true);

    COSArray referenceArray = new COSArray();
    referenceArray.add(referenceDict);
    sigDict.setItem("Reference", referenceArray);
    referenceArray.setNeedToBeUpdated(true);

    // Catalog
    COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
    COSDictionary permsDict = new COSDictionary();
    catalogDict.setItem(COSName.PERMS, permsDict);
    permsDict.setItem(COSName.DOCMDP, signature);
    catalogDict.setNeedToBeUpdated(true);
    permsDict.setNeedToBeUpdated(true);
}

From source file:fixture.pdfboxeg.CreateSignatureBase.java

License:Apache License

public void setMDPPermission(PDDocument doc, PDSignature signature, int accessPermissions) {
    COSDictionary sigDict = signature.getCOSObject();

    // DocMDP specific stuff
    COSDictionary transformParameters = new COSDictionary();
    transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
    transformParameters.setInt(COSName.P, accessPermissions);
    transformParameters.setName(COSName.V, "1.2");
    transformParameters.setNeedToBeUpdated(true);

    COSDictionary referenceDict = new COSDictionary();
    referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
    referenceDict.setItem("TransformMethod", COSName.getPDFName("DocMDP"));
    referenceDict.setItem("DigestMethod", COSName.getPDFName("SHA1"));
    referenceDict.setItem("TransformParams", transformParameters);
    referenceDict.setNeedToBeUpdated(true);

    COSArray referenceArray = new COSArray();
    referenceArray.add(referenceDict);/*from   w  ww. j  a  va  2  s . c o m*/
    sigDict.setItem("Reference", referenceArray);
    referenceArray.setNeedToBeUpdated(true);

    // Catalog
    COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
    COSDictionary permsDict = new COSDictionary();
    catalogDict.setItem(COSName.PERMS, permsDict);
    permsDict.setItem(COSName.DOCMDP, signature);
    catalogDict.setNeedToBeUpdated(true);
    permsDict.setNeedToBeUpdated(true);
}

From source file:test.be.fedict.eid.applet.PdfSpikeTest.java

License:Open Source License

@Test
public void testSignPDF() throws Exception {
    // create a sample PDF file
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();//from  w w w  . ja  va  2s  .co  m

    Paragraph titleParagraph = new Paragraph("This is a test.");
    titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(titleParagraph);

    document.newPage();
    Paragraph textParagraph = new Paragraph("Hello world.");
    document.add(textParagraph);

    document.close();

    File tmpFile = File.createTempFile("test-", ".pdf");
    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(tmpFile, baos.toByteArray());

    // eID
    PcscEid pcscEid = new PcscEid(new TestView(), new Messages(Locale.getDefault()));
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();
    }

    List<X509Certificate> signCertificateChain = pcscEid.getSignCertificateChain();
    Certificate[] certs = new Certificate[signCertificateChain.size()];
    for (int idx = 0; idx < certs.length; idx++) {
        certs[idx] = signCertificateChain.get(idx);
    }

    // open the pdf
    FileInputStream pdfInputStream = new FileInputStream(tmpFile);
    File signedTmpFile = File.createTempFile("test-signed-", ".pdf");
    PdfReader reader = new PdfReader(pdfInputStream);
    FileOutputStream pdfOutputStream = new FileOutputStream(signedTmpFile);
    PdfStamper stamper = PdfStamper.createSignature(reader, pdfOutputStream, '\0', null, true);

    // add extra page
    Rectangle pageSize = reader.getPageSize(1);
    int pageCount = reader.getNumberOfPages();
    int extraPageIndex = pageCount + 1;
    stamper.insertPage(extraPageIndex, pageSize);

    // calculate unique signature field name
    int signatureNameIndex = 1;
    String signatureName;
    AcroFields existingAcroFields = reader.getAcroFields();
    List<String> existingSignatureNames = existingAcroFields.getSignatureNames();
    do {
        signatureName = "Signature" + signatureNameIndex;
        signatureNameIndex++;
    } while (existingSignatureNames.contains(signatureName));
    LOG.debug("new unique signature name: " + signatureName);

    PdfSignatureAppearance signatureAppearance = stamper.getSignatureAppearance();
    signatureAppearance.setCrypto(null, certs, null, PdfSignatureAppearance.SELF_SIGNED);
    signatureAppearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    signatureAppearance.setReason("PDF Signature Test");
    signatureAppearance.setLocation("Belgium");
    signatureAppearance.setVisibleSignature(new Rectangle(54, 440, 234, 566), extraPageIndex, signatureName);
    signatureAppearance.setExternalDigest(new byte[128], new byte[20], "RSA");
    signatureAppearance.preClose();

    byte[] content = IOUtils.toByteArray(signatureAppearance.getRangeStream());
    byte[] hash = MessageDigest.getInstance("SHA-1").digest(content);
    byte[] signatureBytes = pcscEid.sign(hash, "SHA-1");
    pcscEid.close();

    PdfSigGenericPKCS sigStandard = signatureAppearance.getSigStandard();
    PdfPKCS7 signature = sigStandard.getSigner();
    signature.setExternalDigest(signatureBytes, hash, "RSA");
    PdfDictionary dictionary = new PdfDictionary();
    dictionary.put(PdfName.CONTENTS, new PdfString(signature.getEncodedPKCS1()).setHexWriting(true));
    signatureAppearance.close(dictionary);

    LOG.debug("signed tmp file: " + signedTmpFile.getAbsolutePath());

    // verify the signature
    reader = new PdfReader(new FileInputStream(signedTmpFile));
    AcroFields acroFields = reader.getAcroFields();
    ArrayList<String> signatureNames = acroFields.getSignatureNames();
    for (String signName : signatureNames) {
        LOG.debug("signature name: " + signName);
        LOG.debug("signature covers whole document: " + acroFields.signatureCoversWholeDocument(signName));
        LOG.debug("document revision " + acroFields.getRevision(signName) + " of "
                + acroFields.getTotalRevisions());
        PdfPKCS7 pkcs7 = acroFields.verifySignature(signName);
        Calendar signDate = pkcs7.getSignDate();
        LOG.debug("signing date: " + signDate.getTime());
        LOG.debug("Subject: " + PdfPKCS7.getSubjectFields(pkcs7.getSigningCertificate()));
        LOG.debug("Document modified: " + !pkcs7.verify());
        Certificate[] verifyCerts = pkcs7.getCertificates();
        for (Certificate certificate : verifyCerts) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            LOG.debug("cert subject: " + x509Certificate.getSubjectX500Principal());
        }
    }

    /*
     * Reading the signature using Apache PDFBox.
     */
    PDDocument pdDocument = PDDocument.load(signedTmpFile);
    COSDictionary trailer = pdDocument.getDocument().getTrailer();
    /*
     * PDF Reference - third edition - Adobe Portable Document Format -
     * Version 1.4 - 3.6.1 Document Catalog
     */
    COSDictionary documentCatalog = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);

    /*
     * 8.6.1 Interactive Form Dictionary
     */
    COSDictionary acroForm = (COSDictionary) documentCatalog.getDictionaryObject(COSName.ACRO_FORM);

    COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
    for (int fieldIdx = 0; fieldIdx < fields.size(); fieldIdx++) {
        COSDictionary field = (COSDictionary) fields.getObject(fieldIdx);
        String fieldType = field.getNameAsString("FT");
        if ("Sig".equals(fieldType)) {
            COSDictionary signatureDictionary = (COSDictionary) field.getDictionaryObject(COSName.V);
            /*
             * TABLE 8.60 Entries in a signature dictionary
             */
            COSString signatoryName = (COSString) signatureDictionary.getDictionaryObject(COSName.NAME);
            if (null != signatoryName) {
                LOG.debug("signatory name: " + signatoryName.getString());
            }
            COSString reason = (COSString) signatureDictionary.getDictionaryObject(COSName.REASON);
            if (null != reason) {
                LOG.debug("reason: " + reason.getString());
            }
            COSString location = (COSString) signatureDictionary.getDictionaryObject(COSName.LOCATION);
            if (null != location) {
                LOG.debug("location: " + location.getString());
            }
            Calendar signingTime = signatureDictionary.getDate(COSName.M);
            if (null != signingTime) {
                LOG.debug("signing time: " + signingTime.getTime());
            }
            String signatureHandler = signatureDictionary.getNameAsString(COSName.FILTER);
            LOG.debug("signature handler: " + signatureHandler);
        }
    }
}