Search in sources :

Example 71 with OPCPackage

use of org.apache.poi.openxml4j.opc.OPCPackage in project poi by apache.

the class SignatureInfo method writeDocument.

/**
     * Write XML signature into the OPC package
     *
     * @param document the xml signature document
     * @throws MarshalException
     */
protected void writeDocument(Document document) throws MarshalException {
    XmlOptions xo = new XmlOptions();
    Map<String, String> namespaceMap = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : signatureConfig.getNamespacePrefixes().entrySet()) {
        namespaceMap.put(entry.getValue(), entry.getKey());
    }
    xo.setSaveSuggestedPrefixes(namespaceMap);
    xo.setUseDefaultNamespace();
    LOG.log(POILogger.DEBUG, "output signed Office OpenXML document");
    /*
         * Copy the original OOXML content to the signed OOXML package. During
         * copying some files need to changed.
         */
    OPCPackage pkg = signatureConfig.getOpcPackage();
    PackagePartName sigPartName, sigsPartName;
    try {
        // <Override PartName="/_xmlsignatures/sig1.xml" ContentType="application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"/>
        sigPartName = PackagingURIHelper.createPartName("/_xmlsignatures/sig1.xml");
        // <Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/>
        sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs");
    } catch (InvalidFormatException e) {
        throw new MarshalException(e);
    }
    PackagePart sigPart = pkg.getPart(sigPartName);
    if (sigPart == null) {
        sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);
    }
    try {
        OutputStream os = sigPart.getOutputStream();
        SignatureDocument sigDoc = SignatureDocument.Factory.parse(document, DEFAULT_XML_OPTIONS);
        sigDoc.save(os, xo);
        os.close();
    } catch (Exception e) {
        throw new MarshalException("Unable to write signature document", e);
    }
    PackagePart sigsPart = pkg.getPart(sigsPartName);
    if (sigsPart == null) {
        // touch empty marker file
        sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART);
    }
    PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
    for (PackageRelationship pr : relCol) {
        pkg.removeRelationship(pr.getId());
    }
    pkg.addRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
    sigsPart.addRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE);
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) MarshalException(javax.xml.crypto.MarshalException) SignatureDocument(org.w3.x2000.x09.xmldsig.SignatureDocument) HashMap(java.util.HashMap) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) XmlOptions(org.apache.xmlbeans.XmlOptions) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) GeneralSecurityException(java.security.GeneralSecurityException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) SAXException(org.xml.sax.SAXException) MarshalException(javax.xml.crypto.MarshalException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) XmlException(org.apache.xmlbeans.XmlException) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) Map(java.util.Map) HashMap(java.util.HashMap) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage)

Example 72 with OPCPackage

use of org.apache.poi.openxml4j.opc.OPCPackage in project poi by apache.

the class OOXMLSignatureFacet method addManifestReferences.

@SuppressWarnings("resource")
protected void addManifestReferences(List<Reference> manifestReferences) throws XMLSignatureException {
    OPCPackage ooxml = signatureConfig.getOpcPackage();
    List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);
    Set<String> digestedPartNames = new HashSet<String>();
    for (PackagePart pp : relsEntryNames) {
        String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");
        PackageRelationshipCollection prc;
        try {
            prc = new PackageRelationshipCollection(ooxml);
            prc.parseRelationshipsPart(pp);
        } catch (InvalidFormatException e) {
            throw new XMLSignatureException("Invalid relationship descriptor: " + pp.getPartName().getName(), e);
        }
        RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
        for (PackageRelationship relationship : prc) {
            String relationshipType = relationship.getRelationshipType();
            /*
                 * ECMA-376 Part 2 - 3rd edition
                 * 13.2.4.16 Manifest Element
                 * "The producer shall not create a Manifest element that references any data outside of the package."
                 */
            if (TargetMode.EXTERNAL == relationship.getTargetMode()) {
                continue;
            }
            if (!isSignedRelationship(relationshipType))
                continue;
            parameterSpec.addRelationshipReference(relationship.getId());
            // TODO: find a better way ...
            String partName = relationship.getTargetURI().toString();
            if (!partName.startsWith(baseUri)) {
                partName = baseUri + partName;
            }
            try {
                partName = new URI(partName).normalize().getPath().replace('\\', '/');
                LOG.log(POILogger.DEBUG, "part name: " + partName);
            } catch (URISyntaxException e) {
                throw new XMLSignatureException(e);
            }
            String contentType;
            try {
                PackagePartName relName = PackagingURIHelper.createPartName(partName);
                PackagePart pp2 = ooxml.getPart(relName);
                contentType = pp2.getContentType();
            } catch (InvalidFormatException e) {
                throw new XMLSignatureException(e);
            }
            if (relationshipType.endsWith("customXml") && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) {
                LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType);
                continue;
            }
            if (!digestedPartNames.contains(partName)) {
                // We only digest a part once.
                String uri = partName + "?ContentType=" + contentType;
                Reference reference = newReference(uri, null, null, null, null);
                manifestReferences.add(reference);
                digestedPartNames.add(partName);
            }
        }
        if (parameterSpec.hasSourceIds()) {
            List<Transform> transforms = new ArrayList<Transform>();
            transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
            transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE));
            String uri = pp.getPartName().getName() + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
            Reference reference = newReference(uri, transforms, null, null, null);
            manifestReferences.add(reference);
        }
    }
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) URI(java.net.URI) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) RelationshipTransformParameterSpec(org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService.RelationshipTransformParameterSpec) Transform(javax.xml.crypto.dsig.Transform) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) HashSet(java.util.HashSet)

Example 73 with OPCPackage

use of org.apache.poi.openxml4j.opc.OPCPackage in project poi by apache.

the class WorkbookFactory method create.

/**
     * Creates a Workbook from the given NPOIFSFileSystem, which may
     *  be password protected
     *
     *  @param fs The {@link NPOIFSFileSystem} to read the document from
     *  @param password The password that should be used or null if no password is necessary.
     *
     *  @return The created Workbook
     *
     *  @throws IOException if an error occurs while reading the data
     *  @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook}
     */
private static Workbook create(final NPOIFSFileSystem fs, String password) throws IOException, InvalidFormatException {
    DirectoryNode root = fs.getRoot();
    // Encrypted OOXML files go inside OLE2 containers, is this one?
    if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
        InputStream stream = DocumentFactoryHelper.getDecryptedStream(fs, password);
        OPCPackage pkg = OPCPackage.open(stream);
        return create(pkg);
    }
    // So, treat it as a regular HSSF XLS one
    if (password != null) {
        Biff8EncryptionKey.setCurrentUserPassword(password);
    }
    try {
        return new HSSFWorkbook(root, true);
    } finally {
        Biff8EncryptionKey.setCurrentUserPassword(null);
    }
}
Also used : PushbackInputStream(java.io.PushbackInputStream) InputStream(java.io.InputStream) DirectoryNode(org.apache.poi.poifs.filesystem.DirectoryNode) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook)

Example 74 with OPCPackage

use of org.apache.poi.openxml4j.opc.OPCPackage in project poi by apache.

the class TestXSLFPowerPointExtractor method testGetSimpleText.

/**
	 * Get text out of the simple file
	 * @throws XmlException
	 * @throws OpenXML4JException
	 */
@Test
public void testGetSimpleText() throws IOException, XmlException, OpenXML4JException {
    XMLSlideShow xmlA = openPPTX("sample.pptx");
    @SuppressWarnings("resource") OPCPackage pkg = xmlA.getPackage();
    new XSLFPowerPointExtractor(xmlA).close();
    new XSLFPowerPointExtractor(pkg).close();
    XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xmlA);
    extractor.getText();
    String text = extractor.getText();
    assertTrue(text.length() > 0);
    // Check Basics
    assertStartsWith(text, "Lorem ipsum dolor sit amet\n");
    assertContains(text, "amet\n\n");
    // Our placeholder master text
    // This shouldn't show up in the output
    // String masterText =
    //     "Click to edit Master title style\n" +
    //     "Click to edit Master subtitle style\n" +
    //     "\n\n\n\n\n\n" +
    //     "Click to edit Master title style\n" +
    //     "Click to edit Master text styles\n" +
    //     "Second level\n" +
    //     "Third level\n" +
    //     "Fourth level\n" +
    //     "Fifth level\n";
    // Just slides, no notes
    text = extractor.getText(true, false, false);
    String slideText = "Lorem ipsum dolor sit amet\n" + "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + "\n" + "Lorem ipsum dolor sit amet\n" + "Lorem\n" + "ipsum\n" + "dolor\n" + "sit\n" + "amet\n" + "\n";
    assertEquals(slideText, text);
    // Just notes, no slides
    text = extractor.getText(false, true);
    assertEquals("\n\n1\n\n\n2\n", text);
    // Both
    text = extractor.getText(true, true, false);
    String bothText = "Lorem ipsum dolor sit amet\n" + "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + "\n\n\n1\n" + "Lorem ipsum dolor sit amet\n" + "Lorem\n" + "ipsum\n" + "dolor\n" + "sit\n" + "amet\n" + "\n\n\n2\n";
    assertEquals(bothText, text);
    // With Slides and Master Text
    text = extractor.getText(true, false, true);
    String smText = "Lorem ipsum dolor sit amet\n" + "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + "\n" + "Lorem ipsum dolor sit amet\n" + "Lorem\n" + "ipsum\n" + "dolor\n" + "sit\n" + "amet\n" + "\n";
    assertEquals(smText, text);
    // With Slides, Notes and Master Text
    text = extractor.getText(true, true, true);
    String snmText = "Lorem ipsum dolor sit amet\n" + "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + "\n\n\n1\n" + "Lorem ipsum dolor sit amet\n" + "Lorem\n" + "ipsum\n" + "dolor\n" + "sit\n" + "amet\n" + "\n\n\n2\n";
    assertEquals(snmText, text);
    // Via set defaults
    extractor.setSlidesByDefault(false);
    extractor.setNotesByDefault(true);
    text = extractor.getText();
    assertEquals("\n\n1\n\n\n2\n", text);
    extractor.close();
    xmlA.close();
}
Also used : XMLSlideShow(org.apache.poi.xslf.usermodel.XMLSlideShow) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) Test(org.junit.Test)

Example 75 with OPCPackage

use of org.apache.poi.openxml4j.opc.OPCPackage in project poi by apache.

the class TestSignatureInfo method testSignSpreadsheetWithSignatureInfo.

@Test
public void testSignSpreadsheetWithSignatureInfo() throws Exception {
    initKeyPair("Test", "CN=Test");
    String testFile = "hello-world-unsigned.xlsx";
    OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
    SignatureConfig sic = new SignatureConfig();
    sic.setOpcPackage(pkg);
    sic.setKey(keyPair.getPrivate());
    sic.setSigningCertificateChain(Collections.singletonList(x509));
    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(sic);
    // hash > sha1 doesn't work in excel viewer ...
    si.confirmSignature();
    List<X509Certificate> result = new ArrayList<X509Certificate>();
    for (SignaturePart sp : si.getSignatureParts()) {
        if (sp.validate()) {
            result.add(sp.getSigner());
        }
    }
    assertEquals(1, result.size());
    pkg.close();
}
Also used : SignatureInfo(org.apache.poi.poifs.crypt.dsig.SignatureInfo) SignatureConfig(org.apache.poi.poifs.crypt.dsig.SignatureConfig) ArrayList(java.util.ArrayList) SignaturePart(org.apache.poi.poifs.crypt.dsig.SignatureInfo.SignaturePart) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Aggregations

OPCPackage (org.apache.poi.openxml4j.opc.OPCPackage)116 Test (org.junit.Test)54 InputStream (java.io.InputStream)29 PackagePart (org.apache.poi.openxml4j.opc.PackagePart)25 InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)21 File (java.io.File)19 IOException (java.io.IOException)17 PackagePartName (org.apache.poi.openxml4j.opc.PackagePartName)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 XSSFWorkbook (org.apache.poi.xssf.usermodel.XSSFWorkbook)13 SignatureConfig (org.apache.poi.poifs.crypt.dsig.SignatureConfig)10 SignatureInfo (org.apache.poi.poifs.crypt.dsig.SignatureInfo)10 XSSFReader (org.apache.poi.xssf.eventusermodel.XSSFReader)10 OutputStream (java.io.OutputStream)9 ArrayList (java.util.ArrayList)9 FileOutputStream (java.io.FileOutputStream)8 InvalidOperationException (org.apache.poi.openxml4j.exceptions.InvalidOperationException)8 XmlException (org.apache.xmlbeans.XmlException)8 FileInputStream (java.io.FileInputStream)7