Moved prefix logic in one place

git-svn-id: https://svn.apache.org/repos/asf/poi/branches/xml_signature@1628029 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2014-09-28 00:30:05 +00:00
parent 013bd1469c
commit ab5a1dd5d3
7 changed files with 336 additions and 305 deletions

View File

@ -35,7 +35,6 @@ import javax.xml.crypto.dsig.CanonicalizationMethod;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.crypt.dsig.SignatureInfo.SignCreationListener;
import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet; import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet;
import org.apache.poi.poifs.crypt.dsig.facets.OOXMLSignatureFacet; import org.apache.poi.poifs.crypt.dsig.facets.OOXMLSignatureFacet;
import org.apache.poi.poifs.crypt.dsig.facets.Office2010SignatureFacet; import org.apache.poi.poifs.crypt.dsig.facets.Office2010SignatureFacet;
@ -162,7 +161,7 @@ public class SignatureConfig {
if (onlyValidation) return; if (onlyValidation) return;
if (signCreationListener == null) { if (signCreationListener == null) {
signCreationListener = new SignCreationListener(); signCreationListener = new SignatureMarshalListener();
} }
if (signCreationListener instanceof SignatureConfigurable) { if (signCreationListener instanceof SignatureConfigurable) {

View File

@ -24,9 +24,7 @@
package org.apache.poi.poifs.crypt.dsig; package org.apache.poi.poifs.crypt.dsig;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS; import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
@ -82,6 +80,7 @@ import org.apache.jcp.xml.dsig.internal.dom.DOMReference;
import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo; import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo;
import org.apache.poi.EncryptedDocumentException; import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName; import org.apache.poi.openxml4j.opc.PackagePartName;
@ -107,12 +106,9 @@ import org.apache.xmlbeans.XmlOptions;
import org.w3.x2000.x09.xmldsig.SignatureDocument; import org.w3.x2000.x09.xmldsig.SignatureDocument;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget; import org.w3c.dom.events.EventTarget;
import org.w3c.dom.events.MutationEvent;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
public class SignatureInfo implements SignatureConfigurable { public class SignatureInfo implements SignatureConfigurable {
@ -203,38 +199,6 @@ public class SignatureInfo implements SignatureConfigurable {
} }
} }
protected static class SignCreationListener implements EventListener, SignatureConfigurable {
ThreadLocal<EventTarget> target = new ThreadLocal<EventTarget>();
SignatureConfig signatureConfig;
public void setEventTarget(EventTarget target) {
this.target.set(target);
}
public void handleEvent(Event e) {
if (e instanceof MutationEvent) {
MutationEvent mutEvt = (MutationEvent)e;
EventTarget et = mutEvt.getTarget();
if (et instanceof Element) {
Element el = (Element)mutEvt.getTarget();
String packageId = signatureConfig.getPackageSignatureId();
if (el.hasAttribute("Id")) {
el.setIdAttribute("Id", true);
if (packageId.equals(el.getAttribute("Id"))) {
target.get().removeEventListener("DOMSubtreeModified", this, false);
el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS);
target.get().addEventListener("DOMSubtreeModified", this, false);
}
}
}
}
}
public void setSignatureConfig(SignatureConfig signatureConfig) {
this.signatureConfig = signatureConfig;
}
}
public SignatureInfo() { public SignatureInfo() {
initXmlProvider(); initXmlProvider();
} }
@ -360,14 +324,6 @@ public class SignatureInfo implements SignatureConfigurable {
throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!"); throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!");
} }
public static void setPrefix(Node el, String ns, String prefix) {
if (ns.equals(el.getNamespaceURI())) el.setPrefix(prefix);
NodeList nl = el.getChildNodes();
for (int i=0; i<nl.getLength(); i++) {
setPrefix(nl.item(i), ns, prefix);
}
}
protected byte[] getHashMagic() { protected byte[] getHashMagic() {
switch (signatureConfig.getDigestAlgo()) { switch (signatureConfig.getDigestAlgo()) {
case sha1: return SHA1_DIGEST_INFO_PREFIX; case sha1: return SHA1_DIGEST_INFO_PREFIX;
@ -424,10 +380,10 @@ public class SignatureInfo implements SignatureConfigurable {
EventTarget target = (EventTarget)document; EventTarget target = (EventTarget)document;
EventListener creationListener = signatureConfig.getSignCreationListener(); EventListener creationListener = signatureConfig.getSignCreationListener();
if (creationListener != null) { if (creationListener != null) {
if (creationListener instanceof SignCreationListener) { if (creationListener instanceof SignatureMarshalListener) {
((SignCreationListener)creationListener).setEventTarget(target); ((SignatureMarshalListener)creationListener).setEventTarget(target);
} }
target.addEventListener("DOMSubtreeModified", creationListener, false); SignatureMarshalListener.setListener(target, creationListener, true);
} }
/* /*
@ -442,7 +398,7 @@ public class SignatureInfo implements SignatureConfigurable {
for (Map.Entry<String,String> me : signatureConfig.getNamespacePrefixes().entrySet()) { for (Map.Entry<String,String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue()); xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
} }
xmlSignContext.setDefaultNamespacePrefix(signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS)); xmlSignContext.setDefaultNamespacePrefix(""); // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
XMLSignatureFactory signatureFactory = SignatureInfo.getSignatureFactory(); XMLSignatureFactory signatureFactory = SignatureInfo.getSignatureFactory();
@ -611,10 +567,9 @@ public class SignatureInfo implements SignatureConfigurable {
throw new IOException(e); throw new IOException(e);
} }
String sigContentType = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml";
PackagePart sigPart = pkg.getPart(sigPartName); PackagePart sigPart = pkg.getPart(sigPartName);
if (sigPart == null) { if (sigPart == null) {
sigPart = pkg.createPart(sigPartName, sigContentType); sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);
} }
OutputStream os = sigPart.getOutputStream(); OutputStream os = sigPart.getOutputStream();
@ -622,11 +577,10 @@ public class SignatureInfo implements SignatureConfigurable {
sigDoc.save(os, xo); sigDoc.save(os, xo);
os.close(); os.close();
String sigsContentType = "application/vnd.openxmlformats-package.digital-signature-origin";
PackagePart sigsPart = pkg.getPart(sigsPartName); PackagePart sigsPart = pkg.getPart(sigsPartName);
if (sigsPart == null) { if (sigsPart == null) {
// touch empty marker file // touch empty marker file
sigsPart = pkg.createPart(sigsPartName, sigsContentType); sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART);
} }
PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN); PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);

View File

@ -0,0 +1,92 @@
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.poifs.crypt.dsig;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS;
import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.events.MutationEvent;
/**
* This listener class is used, to modify the to be digested xml document,
* e.g. to register id attributes or set prefixes for registered namespaces
*/
public class SignatureMarshalListener implements EventListener, SignatureConfigurable {
ThreadLocal<EventTarget> target = new ThreadLocal<EventTarget>();
SignatureConfig signatureConfig;
public void setEventTarget(EventTarget target) {
this.target.set(target);
}
public void handleEvent(Event e) {
if (!(e instanceof MutationEvent)) return;
MutationEvent mutEvt = (MutationEvent)e;
EventTarget et = mutEvt.getTarget();
if (!(et instanceof Element)) return;
handleElement((Element)et);
}
public void handleElement(Element el) {
EventTarget target = this.target.get();
String packageId = signatureConfig.getPackageSignatureId();
if (el.hasAttribute("Id")) {
el.setIdAttribute("Id", true);
}
setListener(target, this, false);
if (packageId.equals(el.getAttribute("Id"))) {
el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS);
}
setPrefix(el);
setListener(target, this, true);
}
// helper method to keep it in one place
public static void setListener(EventTarget target, EventListener listener, boolean enabled) {
String type = "DOMSubtreeModified";
boolean useCapture = false;
if (enabled) {
target.addEventListener(type, listener, useCapture);
} else {
target.removeEventListener(type, listener, useCapture);
}
}
protected void setPrefix(Node el) {
String prefix = signatureConfig.getNamespacePrefixes().get(el.getNamespaceURI());
if (prefix != null && el.getPrefix() == null) {
el.setPrefix(prefix);
}
NodeList nl = el.getChildNodes();
for (int i=0; i<nl.getLength(); i++) {
setPrefix(nl.item(i));
}
}
public void setSignatureConfig(SignatureConfig signatureConfig) {
this.signatureConfig = signatureConfig;
}
}

View File

@ -31,9 +31,9 @@ import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.xml.crypto.MarshalException; import javax.xml.crypto.MarshalException;
import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.XMLObject; import javax.xml.crypto.dsig.XMLObject;
@ -139,11 +139,12 @@ public class KeyInfoSignatureFacet implements SignatureFacet {
Element n = document.getDocumentElement(); Element n = document.getDocumentElement();
DOMSignContext domSignContext = new DOMSignContext(key, n, nextSibling); DOMSignContext domSignContext = new DOMSignContext(key, n, nextSibling);
DOMCryptoContext domCryptoContext = domSignContext; for (Map.Entry<String,String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
domCryptoContext.putNamespacePrefix(XML_DIGSIG_NS, "xd"); domSignContext.putNamespacePrefix(me.getKey(), me.getValue());
}
DOMStructure domStructure = new DOMStructure(n); DOMStructure domStructure = new DOMStructure(n);
// how to set nextSibling??? - marshal is ignoring nextSibling in DOMSignContext domKeyInfo.marshal(domStructure, domSignContext);
domKeyInfo.marshal(domStructure, domCryptoContext);
// move keyinfo into the right place // move keyinfo into the right place
if (nextSibling != null) { if (nextSibling != null) {

View File

@ -24,8 +24,6 @@
package org.apache.poi.poifs.crypt.dsig.facets; package org.apache.poi.poifs.crypt.dsig.facets;
import static org.apache.poi.poifs.crypt.dsig.SignatureInfo.setPrefix;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -40,6 +38,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import javax.xml.XMLConstants;
import javax.xml.crypto.XMLStructure; import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.CanonicalizationMethod;
@ -104,11 +103,12 @@ public class OOXMLSignatureFacet implements SignatureFacet {
addSignatureInfo(document, signatureFactory, references, objects); addSignatureInfo(document, signatureFactory, references, objects);
} }
private void addManifestObject(Document document, protected void addManifestObject(
XMLSignatureFactory signatureFactory, Document document
List<Reference> references, , XMLSignatureFactory signatureFactory
List<XMLObject> objects) throws NoSuchAlgorithmException, , List<Reference> references
InvalidAlgorithmParameterException, IOException, URISyntaxException, XmlException { , List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, URISyntaxException, XmlException {
List<Reference> manifestReferences = new ArrayList<Reference>(); List<Reference> manifestReferences = new ArrayList<Reference>();
addManifestReferences(signatureFactory, manifestReferences); addManifestReferences(signatureFactory, manifestReferences);
@ -129,14 +129,13 @@ public class OOXMLSignatureFacet implements SignatureFacet {
references.add(reference); references.add(reference);
} }
private void addManifestReferences(XMLSignatureFactory signatureFactory, List<Reference> manifestReferences) protected void addManifestReferences
throws IOException, NoSuchAlgorithmException, (XMLSignatureFactory signatureFactory, List<Reference> manifestReferences)
InvalidAlgorithmParameterException, URISyntaxException, XmlException { throws IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, URISyntaxException, XmlException {
OPCPackage ooxml = this.signatureConfig.getOpcPackage(); OPCPackage ooxml = signatureConfig.getOpcPackage();
List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART); List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);
DigestMethod digestMethod = signatureFactory.newDigestMethod(signatureConfig.getDigestAlgo().xmlSignUri, null); DigestMethod digestMethod = signatureFactory.newDigestMethod(signatureConfig.getDigestAlgo().xmlSignUri, null);
Set<String> digestedPartNames = new HashSet<String>(); Set<String> digestedPartNames = new HashSet<String>();
for (PackagePart pp : relsEntryNames) { for (PackagePart pp : relsEntryNames) {
@ -154,12 +153,12 @@ public class OOXMLSignatureFacet implements SignatureFacet {
for (PackageRelationship relationship : prc) { for (PackageRelationship relationship : prc) {
String relationshipType = relationship.getRelationshipType(); 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()) { if (TargetMode.EXTERNAL == relationship.getTargetMode()) {
/*
* 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."
*/
continue; continue;
} }
@ -180,6 +179,7 @@ public class OOXMLSignatureFacet implements SignatureFacet {
} catch (InvalidFormatException e) { } catch (InvalidFormatException e) {
throw new IOException(e); throw new IOException(e);
} }
if (relationshipType.endsWith("customXml") if (relationshipType.endsWith("customXml")
&& !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) { && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) {
LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType); LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType);
@ -198,11 +198,11 @@ public class OOXMLSignatureFacet implements SignatureFacet {
if (parameterSpec.hasSourceIds()) { if (parameterSpec.hasSourceIds()) {
List<Transform> transforms = new ArrayList<Transform>(); List<Transform> transforms = new ArrayList<Transform>();
transforms.add(signatureFactory.newTransform( transforms.add(signatureFactory.newTransform(
RelationshipTransformService.TRANSFORM_URI, RelationshipTransformService.TRANSFORM_URI,
parameterSpec)); parameterSpec));
transforms.add(signatureFactory.newTransform( transforms.add(signatureFactory.newTransform(
CanonicalizationMethod.INCLUSIVE, CanonicalizationMethod.INCLUSIVE,
(TransformParameterSpec) null)); (TransformParameterSpec) null));
String uri = pp.getPartName().getName() String uri = pp.getPartName().getName()
+ "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
Reference reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null); Reference reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null);
@ -212,15 +212,16 @@ public class OOXMLSignatureFacet implements SignatureFacet {
} }
private void addSignatureTime(Document document, protected void addSignatureTime(
XMLSignatureFactory signatureFactory, Document document
List<XMLStructure> objectContent) { , XMLSignatureFactory signatureFactory
, List<XMLStructure> objectContent) {
/* /*
* SignatureTime * SignatureTime
*/ */
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
fmt.setTimeZone(TimeZone.getTimeZone("UTC")); fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
String nowStr = fmt.format(this.signatureConfig.getExecutionTime()); String nowStr = fmt.format(signatureConfig.getExecutionTime());
LOG.log(POILogger.DEBUG, "now: " + nowStr); LOG.log(POILogger.DEBUG, "now: " + nowStr);
SignatureTimeDocument sigTime = SignatureTimeDocument.Factory.newInstance(); SignatureTimeDocument sigTime = SignatureTimeDocument.Factory.newInstance();
@ -228,24 +229,21 @@ public class OOXMLSignatureFacet implements SignatureFacet {
ctTime.setFormat("YYYY-MM-DDThh:mm:ssTZD"); ctTime.setFormat("YYYY-MM-DDThh:mm:ssTZD");
ctTime.setValue(nowStr); ctTime.setValue(nowStr);
// TODO: find better method to have xmlbeans + export the prefix
Element n = (Element)document.importNode(ctTime.getDomNode(),true); Element n = (Element)document.importNode(ctTime.getDomNode(),true);
setPrefix(n, OO_DIGSIG_NS, "mdssi");
List<XMLStructure> signatureTimeContent = new ArrayList<XMLStructure>(); List<XMLStructure> signatureTimeContent = new ArrayList<XMLStructure>();
signatureTimeContent.add(new DOMStructure(n)); signatureTimeContent.add(new DOMStructure(n));
SignatureProperty signatureTimeSignatureProperty = signatureFactory SignatureProperty signatureTimeSignatureProperty = signatureFactory
.newSignatureProperty(signatureTimeContent, "#" + signatureConfig.getPackageSignatureId(), .newSignatureProperty(signatureTimeContent, "#" + signatureConfig.getPackageSignatureId(),
"idSignatureTime"); "idSignatureTime");
List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>(); List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();
signaturePropertyContent.add(signatureTimeSignatureProperty); signaturePropertyContent.add(signatureTimeSignatureProperty);
SignatureProperties signatureProperties = signatureFactory SignatureProperties signatureProperties = signatureFactory
.newSignatureProperties(signaturePropertyContent, .newSignatureProperties(signaturePropertyContent,
"id-signature-time-" + signatureConfig.getExecutionTime()); "id-signature-time-" + signatureConfig.getExecutionTime());
objectContent.add(signatureProperties); objectContent.add(signatureProperties);
} }
private void addSignatureInfo(Document document, protected void addSignatureInfo(Document document,
XMLSignatureFactory signatureFactory, XMLSignatureFactory signatureFactory,
List<Reference> references, List<Reference> references,
List<XMLObject> objects) List<XMLObject> objects)
@ -256,18 +254,18 @@ public class OOXMLSignatureFacet implements SignatureFacet {
CTSignatureInfoV1 ctSigV1 = sigV1.addNewSignatureInfoV1(); CTSignatureInfoV1 ctSigV1 = sigV1.addNewSignatureInfoV1();
ctSigV1.setManifestHashAlgorithm(signatureConfig.getDigestAlgo().xmlSignUri); ctSigV1.setManifestHashAlgorithm(signatureConfig.getDigestAlgo().xmlSignUri);
Element n = (Element)document.importNode(ctSigV1.getDomNode(), true); Element n = (Element)document.importNode(ctSigV1.getDomNode(), true);
n.setAttributeNS(XML_NS, "xmlns", "http://schemas.microsoft.com/office/2006/digsig"); n.setAttributeNS(XML_NS, XMLConstants.XMLNS_ATTRIBUTE, MS_DIGSIG_NS);
List<XMLStructure> signatureInfoContent = new ArrayList<XMLStructure>(); List<XMLStructure> signatureInfoContent = new ArrayList<XMLStructure>();
signatureInfoContent.add(new DOMStructure(n)); signatureInfoContent.add(new DOMStructure(n));
SignatureProperty signatureInfoSignatureProperty = signatureFactory SignatureProperty signatureInfoSignatureProperty = signatureFactory
.newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(), .newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(),
"idOfficeV1Details"); "idOfficeV1Details");
List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>(); List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();
signaturePropertyContent.add(signatureInfoSignatureProperty); signaturePropertyContent.add(signatureInfoSignatureProperty);
SignatureProperties signatureProperties = signatureFactory SignatureProperties signatureProperties = signatureFactory
.newSignatureProperties(signaturePropertyContent, null); .newSignatureProperties(signaturePropertyContent, null);
objectContent.add(signatureProperties); objectContent.add(signatureProperties);
String objectId = "idOfficeObject"; String objectId = "idOfficeObject";
@ -284,61 +282,17 @@ public class OOXMLSignatureFacet implements SignatureFacet {
// empty // empty
} }
public static String getRelationshipReferenceURI(String zipEntryName) { protected static String getRelationshipReferenceURI(String zipEntryName) {
return "/" return "/"
+ zipEntryName + zipEntryName
+ "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
} }
public static String getResourceReferenceURI(String resourceName, protected static String getResourceReferenceURI(String resourceName, String contentType) {
String contentType) {
return "/" + resourceName + "?ContentType=" + contentType; return "/" + resourceName + "?ContentType=" + contentType;
} }
public static String[] contentTypes = { protected static boolean isSignedRelationship(String relationshipType) {
/*
* Word
*/
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
"application/vnd.openxmlformats-officedocument.theme+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
/*
* Word 2010
*/
"application/vnd.ms-word.stylesWithEffects+xml",
/*
* Excel
*/
"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
/*
* Powerpoint
*/
"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slide+xml",
"application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml",
/*
* Powerpoint 2010
*/
"application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml",
"application/vnd.openxmlformats-officedocument.presentationml.presProps+xml" };
public static boolean isSignedRelationship(String relationshipType) {
LOG.log(POILogger.DEBUG, "relationship type: " + relationshipType); LOG.log(POILogger.DEBUG, "relationship type: " + relationshipType);
for (String signedTypeExtension : signed) { for (String signedTypeExtension : signed) {
if (relationshipType.endsWith(signedTypeExtension)) { if (relationshipType.endsWith(signedTypeExtension)) {
@ -351,155 +305,197 @@ public class OOXMLSignatureFacet implements SignatureFacet {
} }
return false; return false;
} }
public static final String[] contentTypes = {
/*
* Word
*/
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
"application/vnd.openxmlformats-officedocument.theme+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
/*
* Word 2010
*/
"application/vnd.ms-word.stylesWithEffects+xml",
/*
* Excel
*/
"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
/*
* Powerpoint
*/
"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
"application/vnd.openxmlformats-officedocument.presentationml.slide+xml",
"application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml",
/*
* Powerpoint 2010
*/
"application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml",
"application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"
};
/** /**
* Office 2010 list of signed types (extensions). * Office 2010 list of signed types (extensions).
*/ */
public static String[] signed = { "powerPivotData", // public static final String[] signed = {
"activeXControlBinary", // "powerPivotData", //
"attachedToolbars", // "activeXControlBinary", //
"connectorXml", // "attachedToolbars", //
"downRev", // "connectorXml", //
"functionPrototypes", // "downRev", //
"graphicFrameDoc", // "functionPrototypes", //
"groupShapeXml", // "graphicFrameDoc", //
"ink", // "groupShapeXml", //
"keyMapCustomizations", // "ink", //
"legacyDiagramText", // "keyMapCustomizations", //
"legacyDocTextInfo", // "legacyDiagramText", //
"officeDocument", // "legacyDocTextInfo", //
"pictureXml", // "officeDocument", //
"shapeXml", // "pictureXml", //
"smartTags", // "shapeXml", //
"ui/altText", // "smartTags", //
"ui/buttonSize", // "ui/altText", //
"ui/controlID", // "ui/buttonSize", //
"ui/description", // "ui/controlID", //
"ui/enabled", // "ui/description", //
"ui/extensibility", // "ui/enabled", //
"ui/helperText", // "ui/extensibility", //
"ui/imageID", // "ui/helperText", //
"ui/imageMso", // "ui/imageID", //
"ui/keyTip", // "ui/imageMso", //
"ui/label", // "ui/keyTip", //
"ui/lcid", // "ui/label", //
"ui/loud", // "ui/lcid", //
"ui/pressed", // "ui/loud", //
"ui/progID", // "ui/pressed", //
"ui/ribbonID", // "ui/progID", //
"ui/showImage", // "ui/ribbonID", //
"ui/showLabel", // "ui/showImage", //
"ui/supertip", // "ui/showLabel", //
"ui/target", // "ui/supertip", //
"ui/text", // "ui/target", //
"ui/title", // "ui/text", //
"ui/tooltip", // "ui/title", //
"ui/userCustomization", // "ui/tooltip", //
"ui/visible", // "ui/userCustomization", //
"userXmlData", // "ui/visible", //
"vbaProject", // "userXmlData", //
"wordVbaData", // "vbaProject", //
"wsSortMap", // "wordVbaData", //
"xlBinaryIndex", // "wsSortMap", //
"xlExternalLinkPath/xlAlternateStartup", // "xlBinaryIndex", //
"xlExternalLinkPath/xlLibrary", // "xlExternalLinkPath/xlAlternateStartup", //
"xlExternalLinkPath/xlPathMissing", // "xlExternalLinkPath/xlLibrary", //
"xlExternalLinkPath/xlStartup", // "xlExternalLinkPath/xlPathMissing", //
"xlIntlMacrosheet", // "xlExternalLinkPath/xlStartup", //
"xlMacrosheet", // "xlIntlMacrosheet", //
"customData", // "xlMacrosheet", //
"diagramDrawing", // "customData", //
"hdphoto", // "diagramDrawing", //
"inkXml", // "hdphoto", //
"media", // "inkXml", //
"slicer", // "media", //
"slicerCache", // "slicer", //
"stylesWithEffects", // "slicerCache", //
"ui/extensibility", // "stylesWithEffects", //
"chartColorStyle", // "ui/extensibility", //
"chartLayout", // "chartColorStyle", //
"chartStyle", // "chartLayout", //
"dictionary", // "chartStyle", //
"timeline", // "dictionary", //
"timelineCache", // "timeline", //
"aFChunk", // "timelineCache", //
"attachedTemplate", // "aFChunk", //
"audio", // "attachedTemplate", //
"calcChain", // "audio", //
"chart", // "calcChain", //
"chartsheet", // "chart", //
"chartUserShapes", // "chartsheet", //
"commentAuthors", // "chartUserShapes", //
"comments", // "commentAuthors", //
"connections", // "comments", //
"control", // "connections", //
"customProperty", // "control", //
"customXml", // "customProperty", //
"diagramColors", // "customXml", //
"diagramData", // "diagramColors", //
"diagramLayout", // "diagramData", //
"diagramQuickStyle", // "diagramLayout", //
"dialogsheet", // "diagramQuickStyle", //
"drawing", // "dialogsheet", //
"endnotes", // "drawing", //
"externalLink", // "endnotes", //
"externalLinkPath", // "externalLink", //
"font", // "externalLinkPath", //
"fontTable", // "font", //
"footer", // "fontTable", //
"footnotes", // "footer", //
"glossaryDocument", // "footnotes", //
"handoutMaster", // "glossaryDocument", //
"header", // "handoutMaster", //
"hyperlink", // "header", //
"image", // "hyperlink", //
"mailMergeHeaderSource", // "image", //
"mailMergeRecipientData", // "mailMergeHeaderSource", //
"mailMergeSource", // "mailMergeRecipientData", //
"notesMaster", // "mailMergeSource", //
"notesSlide", // "notesMaster", //
"numbering", // "notesSlide", //
"officeDocument", // "numbering", //
"oleObject", // "officeDocument", //
"package", // "oleObject", //
"pivotCacheDefinition", // "package", //
"pivotCacheRecords", // "pivotCacheDefinition", //
"pivotTable", // "pivotCacheRecords", //
"presProps", // "pivotTable", //
"printerSettings", // "presProps", //
"queryTable", // "printerSettings", //
"recipientData", // "queryTable", //
"settings", // "recipientData", //
"sharedStrings", // "settings", //
"sheetMetadata", // "sharedStrings", //
"slide", // "sheetMetadata", //
"slideLayout", // "slide", //
"slideMaster", // "slideLayout", //
"slideUpdateInfo", // "slideMaster", //
"slideUpdateUrl", // "slideUpdateInfo", //
"styles", // "slideUpdateUrl", //
"table", // "styles", //
"tableSingleCells", // "table", //
"tableStyles", // "tableSingleCells", //
"tags", // "tableStyles", //
"theme", // "tags", //
"themeOverride", // "theme", //
"transform", // "themeOverride", //
"video", // "transform", //
"viewProps", // "video", //
"volatileDependencies", // "viewProps", //
"webSettings", // "volatileDependencies", //
"worksheet", // "webSettings", //
"xmlMaps", // "worksheet", //
"ctrlProp", // "xmlMaps", //
"customData", // "ctrlProp", //
"diagram", // "customData", //
"diagramColorsHeader", // "diagram", //
"diagramLayoutHeader", // "diagramColorsHeader", //
"diagramQuickStyleHeader", // "diagramLayoutHeader", //
"documentParts", // "diagramQuickStyleHeader", //
"slicer", // "documentParts", //
"slicerCache", // "slicer", //
"vmlDrawing" // "slicerCache", //
"vmlDrawing" //
}; };
} }

View File

@ -24,8 +24,6 @@
package org.apache.poi.poifs.crypt.dsig.facets; package org.apache.poi.poifs.crypt.dsig.facets;
import static org.apache.poi.poifs.crypt.dsig.SignatureInfo.setPrefix;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -206,14 +204,10 @@ public class XAdESSignatureFacet implements SignatureFacet {
} }
} }
// marshall XAdES QualifyingProperties
// ((Element)qualifyingProperties.getSignedProperties().getDomNode()).setIdAttribute("Id", true);
// add XAdES ds:Object // add XAdES ds:Object
List<XMLStructure> xadesObjectContent = new ArrayList<XMLStructure>(); List<XMLStructure> xadesObjectContent = new ArrayList<XMLStructure>();
Element qualDocEl = (Element)document.importNode(qualifyingProperties.getDomNode(), true); Element qualDocElSrc = (Element)qualifyingProperties.getDomNode();
qualDocEl.setAttributeNS(XML_NS, "xmlns:xd", XADES_132_NS); Element qualDocEl = (Element)document.importNode(qualDocElSrc, true);
setPrefix(qualDocEl, XADES_132_NS, "xd");
xadesObjectContent.add(new DOMStructure(qualDocEl)); xadesObjectContent.add(new DOMStructure(qualDocEl));
XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null); XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null);
objects.add(xadesObject); objects.add(xadesObject);

View File

@ -24,9 +24,6 @@
package org.apache.poi.poifs.crypt.dsig.services; package org.apache.poi.poifs.crypt.dsig.services;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS;
import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
@ -171,8 +168,6 @@ public class RelationshipTransformService extends TransformService {
RelationshipReferenceDocument relRef = RelationshipReferenceDocument.Factory.newInstance(); RelationshipReferenceDocument relRef = RelationshipReferenceDocument.Factory.newInstance();
relRef.addNewRelationshipReference().setSourceId(sourceId); relRef.addNewRelationshipReference().setSourceId(sourceId);
Node n = relRef.getRelationshipReference().getDomNode(); Node n = relRef.getRelationshipReference().getDomNode();
// TODO: is there a more elegant way to do this?
n.setPrefix("mdssi");
n = doc.importNode(n, true); n = doc.importNode(n, true);
parentNode.appendChild(n); parentNode.appendChild(n);
} }