Example usage for org.apache.pdfbox.pdmodel PDDocument load

List of usage examples for org.apache.pdfbox.pdmodel PDDocument load

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument load.

Prototype

public static PDDocument load(byte[] input) throws IOException 

Source Link

Document

Parses a PDF.

Usage

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Test if the PDF is correctly sealed using the {@link SealMethod.SEAL_CUSTOM}
 * /* w  ww .  j  a va2s. c  o  m*/
 * @return true if sealed, false if not
 */
public static boolean isSealedCustom(final byte[] pdf, final SignatureTokenConnection token) {
    PDDocument doc = null;
    try {
        InputStream is = new ByteArrayInputStream(pdf);
        doc = PDDocument.load(is);
        boolean sealed = false;
        byte[] originalReceived;
        if (doc.getSignatureDictionaries() != null && doc.getSignatureDictionaries().size() != 0) {
            // Get the original file
            originalReceived = getOriginalBytes(doc, pdf);
        } else {
            originalReceived = pdf;
        }
        // Extract the original digest
        byte[] originalDigest = unwrapDigest(extractAttachment(originalReceived, DIGEST_FILE_NAME));
        // Extract the attachements
        Set<String> attachementNames = getAttachmentsNames(doc);
        Map<String, byte[]> attachements = new HashMap<String, byte[]>();
        for (String attachementName : attachementNames) {
            byte[] bytes = extractAttachment(originalReceived, attachementName);
            attachements.put(attachementName, new String(bytes, "UTF-8").getBytes());
        }
        doc = PDDocument.load(new ByteArrayInputStream(originalReceived));
        // Remove all the attachemente
        doc = removeAllAttachments(doc);
        originalReceived = toByteArray(doc);
        closeQuietly(doc);
        // Append the attachements we just removed. Because PdfBox is adding \r\n
        originalReceived = appendAttachment(originalReceived, attachements, DIGEST_FILE_NAME);
        byte[] checkDigest = token.sign(originalReceived, DigestAlgorithm.SHA256, token.getKeys().get(0));
        sealed = Arrays.equals(originalDigest, checkDigest);
        return sealed;
    } catch (COSVisitorException e) {
        throw new SigningException(e);
    } catch (IOException e) {
        throw new SigningException(e);
    } finally {
        closeQuietly(doc);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Append an attachment to the PDF. This method will only work for attachments with unique names
 * /*  w  w w  . ja  v a2 s  .c om*/
 * @param pdf the PDF document
 * @param attachment the bytes for the attachment
 * @param fileName the name of the attachment
 */
public static byte[] appendAttachment(byte[] pdf, byte[] attachment, String fileName) {

    try {

        InputStream is = new ByteArrayInputStream(pdf);
        PDDocument doc = PDDocument.load(is);
        Map<String, byte[]> attachments = getAttachments(doc);
        doc = removeAllAttachments(doc);
        attachments.put(fileName, attachment);
        PDDocumentNameDictionary names2 = new PDDocumentNameDictionary(doc.getDocumentCatalog());
        Map<String, COSObjectable> efMap = new HashMap<String, COSObjectable>();
        for (String key : attachments.keySet()) {
            PDComplexFileSpecification afs = new PDComplexFileSpecification();
            afs.setFile(key);
            InputStream isa = new ByteArrayInputStream(attachments.get(key));
            PDEmbeddedFile ef = new PDEmbeddedFile(doc, isa);
            ef.setSize(attachments.get(key).length);
            afs.setEmbeddedFile(ef);
            efMap.put(key, afs);
        }

        PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
        efTree.setNames(efMap);
        names2.setEmbeddedFiles(efTree);
        doc.getDocumentCatalog().setNames(names2);
        return toByteArray(doc);
    } catch (COSVisitorException e) {
        throw new SigningException(e);
    } catch (IOException e) {
        throw new SigningException(e);
    }

}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Append attachments to the PDF.//w w  w  . j av  a  2 s .  c  o m
 * 
 * @param pdf the PDF document
 * @param attachments the bytes for the attachment
 * @param ignore the names to be ignored
 */
public static byte[] appendAttachment(byte[] pdf, Map<String, byte[]> attachments, String... ignore) {

    try {
        List<String> ignoreList = Arrays.asList(ignore);
        InputStream is = new ByteArrayInputStream(pdf);
        PDDocument doc = PDDocument.load(is);
        PDEmbeddedFilesNameTreeNode tree = new PDDocumentNameDictionary(doc.getDocumentCatalog())
                .getEmbeddedFiles();
        if (tree == null) {
            tree = new PDEmbeddedFilesNameTreeNode();
            PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
            names.setEmbeddedFiles(tree);
            doc.getDocumentCatalog().setNames(names);
        }
        Map<String, COSObjectable> temp = tree.getNames();
        Map<String, COSObjectable> map = new HashMap<String, COSObjectable>();
        if (temp != null) {
            map.putAll(temp);
        }
        for (String fileName : attachments.keySet()) {
            if (ignoreList.contains(fileName)) {
                continue;
            }
            byte[] bytes = attachments.get(fileName);
            if (bytes == null) {
                continue;
            }
            PDComplexFileSpecification cosObject = new PDComplexFileSpecification();
            cosObject.setFile(fileName);
            InputStream isa = new ByteArrayInputStream(bytes);
            PDEmbeddedFile ef = new PDEmbeddedFile(doc, isa);
            ef.setSize(bytes.length);
            cosObject.setEmbeddedFile(ef);
            map.put(fileName, cosObject);
        }
        tree.setNames(map);
        return toByteArray(doc);
    } catch (COSVisitorException e) {
        throw new SigningException(e);
    } catch (IOException e) {
        throw new SigningException(e);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Remove all embedded file attachments from the document
 * /* w  w  w. j av a 2s.  co m*/
 * @param doc the document
 * @return the document with
 * @throws COSVisitorException
 * @throws IOException
 */
private static PDDocument removeAllAttachments(PDDocument doc) throws COSVisitorException, IOException {
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    namesDictionary.setEmbeddedFiles(null);
    doc.getDocumentCatalog().setNames(namesDictionary);
    InputStream is = new ByteArrayInputStream(toByteArray(doc));
    return PDDocument.load(is);
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtilsTest.java

License:EUPL

/**
 * Test PDF seal//  ww w .j  av a  2  s.c  om
 * @throws COSVisitorException
 * @throws IOException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 */
@Test
public void testSeal() throws COSVisitorException, IOException, KeyStoreException, NoSuchAlgorithmException {
    //load our test document - an iText PDF as generated by the Portal report service
    InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("dss/testseal.pdf");
    byte[] pdf = IOUtils.toByteArray(is);
    is.close();

    //Attach the form XML
    String attachment = "<xmldata></xmldata>";
    byte[] doc = PdfUtils.appendAttachment(pdf, attachment.getBytes(), "form.xml");

    //Seal the document 
    InputStream isP12 = PdfUtilsTest.class.getClassLoader().getResourceAsStream("dss/test.p12");
    Pkcs12SignatureToken token = new Pkcs12SignatureToken("password", isP12);
    byte[] sealed = PdfUtils.sealPDFCustom(doc, token,
            "This file allows us to check that the form is authentic");

    InputStream isse = new ByteArrayInputStream(sealed);
    PDDocument sealedPDD = PDDocument.load(isse);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    sealedPDD.save(baos);
    sealed = baos.toByteArray();
    //Sign the document (like a portal user should)
    CertificateVerifier cv = new CommonCertificateVerifier();
    PAdESService p = new PAdESService(cv);
    DSSDocument dssDoc = new InMemoryDocument(sealed);

    SignatureParameters params = new SignatureParameters();
    params.setPrivateKeyEntry(token.getKeys().get(0));
    params.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B);
    params.setSigningToken(token);
    params.setDigestAlgorithm(DigestAlgorithm.SHA512);
    Calendar c = GregorianCalendar.getInstance();
    c.set(Calendar.YEAR, 2011);
    params.bLevel().setSigningDate(c.getTime());
    DSSDocument sDoc = p.signDocument(dssDoc, params);
    //Test that the seal is OK.
    assertTrue(TestUtils.isSealed(null, sDoc.getBytes(), token, SealMethod.SEAL_CUSTOM));
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

License:Open Source License

/**
 * These signatures are invalid because of non ordered signed attributes
 *///from w w  w  .  ja va  2  s .co m
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {

    try {/*  w  w w.  ja  v a 2s .c o  m*/
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        PDDocument document = PDDocument.load(inputStream);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        assertEquals(1, signatures.size());

        for (PDSignature pdSignature : signatures) {
            byte[] contents = pdSignature.getContents(byteArray);
            byte[] signedContent = pdSignature.getSignedContent(byteArray);

            logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

            // IOUtils.write(contents, new FileOutputStream("sig.p7s"));

            ASN1InputStream asn1sInput = new ASN1InputStream(contents);
            ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

            logger.info("SEQ : " + asn1Seq.toString());

            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
            assertEquals(PKCSObjectIdentifiers.signedData, oid);

            SignedData signedData = SignedData
                    .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

            ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
            ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                    .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
            logger.info("DIGEST ALGO : " + digestAlgorithm);

            ContentInfo encapContentInfo = signedData.getEncapContentInfo();
            ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
            logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
            int previousSize = 0;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                ASN1ObjectIdentifier attrTypeOid = attribute.getAttrType();
                attributeOids.add(attrTypeOid);
                int size = attrTypeOid.getEncoded().length + attribute.getEncoded().length;
                assertTrue(size >= previousSize);

                previousSize = size;
            }
            logger.info("List of OID for Auth Attrb : " + attributeOids);

            Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
            assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);
            IOUtils.closeQuietly(asn1sInput);
        }

        IOUtils.closeQuietly(inputStream);
        document.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBWithContentTimestampTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    super.onDocumentSigned(byteArray);

    try (PDDocument doc = PDDocument.load(byteArray)) {
        List<PDSignature> signatureDictionaries = doc.getSignatureDictionaries();
        assertEquals(1, signatureDictionaries.size());
        PDSignature pdSignature = signatureDictionaries.get(0);
        assertNotNull(pdSignature.getName());
        assertNotNull(pdSignature.getReason());
        assertNotNull(pdSignature.getLocation());
        assertNotNull(pdSignature.getContactInfo());
        assertNotNull(pdSignature.getSignDate()); // M
        assertEquals("Adobe.PPKLite", pdSignature.getFilter());
        assertEquals("ETSI.CAdES.detached", pdSignature.getSubFilter());
    } catch (IOException e) {
        throw new DSSException(e);
    }/*from w ww  .j  ava2  s.c  o  m*/
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelLTTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {
    try {/*from   w  ww.  j  a va 2  s  .c o  m*/
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);

        PDDocument pdDoc = PDDocument.load(bais);
        List<PDSignature> sigs = pdDoc.getSignatureDictionaries();
        PDSignature pdSignature = sigs.get(0);
        byte[] contents = pdSignature.getContents(byteArray);

        byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA1, contents);
        String hex = Utils.toHex(digest);

        String pdfString = new String(byteArray, "UTF-8");
        assertTrue(pdfString.contains(Utils.upperCase(hex)));
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.pades.signature.PAdESVisibleSignaturePositionTest.java

License:Open Source License

@Test
@Ignore("for pull request #71")
public void rotatePullRequest71Test() throws Exception {
    Logger logger = LoggerFactory.getLogger(getClass());
    /**/*from   w  w w  .j a  va2 s  .co m*/
     * minolta scanner normal(not rotated) pdf and rotation none.
     *
     * You can check the pdf rotation by this code:
     * PDDocument inputPDF = PDDocument.load(getClass().getResourceAsStream("/visualSignature/sun.pdf"));
     * System.out.println("rotation: " + inputPDF.getPage(0).getRotation());
     *
     * result in pdf viewer: signature is top left corner and the sign image line is parallel with the sun eyes line
     *
     * comment: this is the original working
     */
    PDDocument inputPDF = PDDocument.load(getClass().getResourceAsStream("/visualSignature/sun.pdf"));
    logger.info("rotation sun.pdf: " + inputPDF.getPage(0).getRotation());

    SignatureImageParameters signatureImageParameters = createSignatureImageParameters();

    signatureImageParameters.setRotation(SignatureImageParameters.VisualSignatureRotation.NONE);
    DSSDocument document = sign(signablePdfs.get("minoltaScan"));
    File checkPdfFile = new File("target/pdf/check_normal_none.pdf");
    checkPdfFile.getParentFile().mkdirs();
    IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));

    /**
     * minolta scanner rotated pdf and rotation none (in pdf view the rotated and normal pdf seem equal)
     * you can check the pdf rotation by this code:
     * PDDocument inputPDF = PDDocument.load(getClass().getResourceAsStream("/visualSignature/sun_90.pdf"));
     * System.out.println("rotation: " + inputPDF.getPage(0).getRotation());
     *
     * result in pdf viewer: signature is top right corner and the sign image line is perpendicular with the sun
     * eyes line
     *
     * comment: this is the original working
     */
    inputPDF = PDDocument.load(getClass().getResourceAsStream("/visualSignature/sun_90.pdf"));
    logger.info("rotation sun_90.pdf: " + inputPDF.getPage(0).getRotation());

    signatureImageParameters = createSignatureImageParameters();

    signatureImageParameters.setRotation(SignatureImageParameters.VisualSignatureRotation.NONE);
    document = sign(signablePdfs.get("minoltaScan90"));
    checkPdfFile = new File("target/pdf/check_90_none.pdf");
    checkPdfFile.getParentFile().mkdirs();
    IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));

    /**
     * minolta scanner rotated pdf and rotation automatic (in pdf view the rotated and normal pdf seem equal)
     *
     * result in pdf viewer: signature is top left corner and the sign image line is parallel with the sun eyes
     * line,
     * it will be same as with sun.pdf (not rotated) and rotation none
     */
    signatureImageParameters = createSignatureImageParameters();

    signatureImageParameters.setRotation(SignatureImageParameters.VisualSignatureRotation.AUTOMATIC);
    document = sign(signablePdfs.get("minoltaScan90"));
    checkPdfFile = new File("target/pdf/check_90_automatic.pdf");
    checkPdfFile.getParentFile().mkdirs();
    IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));

    /**
     * minolta scanner normal(not rotated) pdf and rotation none.
     *
     * result in pdf viewer: signature is top left corner and the sign image line is parallel with the sun eyes
     * line,
     * it will be same as with sun.pdf (not rotated) and rotation none
     */
    signatureImageParameters = createSignatureImageParameters();

    signatureImageParameters.setRotation(SignatureImageParameters.VisualSignatureRotation.AUTOMATIC);
    document = sign(signablePdfs.get("minoltaScan"));
    checkPdfFile = new File("target/pdf/check_normal_automatic.pdf");
    checkPdfFile.getParentFile().mkdirs();
    IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));
}