certificateChain,
+ RevocationData revocationData) throws Exception;
+}
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/AddressDTO.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/AddressDTO.java
new file mode 100644
index 0000000000..a164046319
--- /dev/null
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/AddressDTO.java
@@ -0,0 +1,51 @@
+/* ====================================================================
+ 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.
+==================================================================== */
+
+/* ====================================================================
+ This product contains an ASLv2 licensed version of the OOXML signer
+ package from the eID Applet project
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ Copyright (C) 2008-2014 FedICT.
+ ================================================================= */
+
+package org.apache.poi.poifs.crypt.dsig.spi;
+
+import java.io.Serializable;
+import java.security.Identity;
+
+/**
+ * Address Data Transfer Object.
+ *
+ * @author Frank Cornelis
+ * @see Identity
+ *
+ */
+public class AddressDTO implements Serializable {
+
+ /*
+ * We implement serializable to allow this class to be used in distributed
+ * containers as defined in the Servlet v2.4 specification.
+ */
+
+ private static final long serialVersionUID = 1L;
+
+ public String streetAndNumber;
+
+ public String zip;
+
+ public String city;
+}
\ No newline at end of file
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/DigestInfo.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/DigestInfo.java
new file mode 100644
index 0000000000..2f7c58c338
--- /dev/null
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/DigestInfo.java
@@ -0,0 +1,56 @@
+/* ====================================================================
+ 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.
+==================================================================== */
+
+/* ====================================================================
+ This product contains an ASLv2 licensed version of the OOXML signer
+ package from the eID Applet project
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ Copyright (C) 2008-2014 FedICT.
+ ================================================================= */
+
+package org.apache.poi.poifs.crypt.dsig.spi;
+
+import java.io.Serializable;
+
+import org.apache.poi.poifs.crypt.HashAlgorithm;
+
+/**
+ * Digest Information data transfer class.
+ */
+public class DigestInfo implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Main constructor.
+ *
+ * @param digestValue
+ * @param hashAlgo
+ * @param description
+ */
+ public DigestInfo(byte[] digestValue, HashAlgorithm hashAlgo, String description) {
+ this.digestValue = digestValue;
+ this.hashAlgo = hashAlgo;
+ this.description = description;
+ }
+
+ public final byte[] digestValue;
+
+ public final String description;
+
+ public final HashAlgorithm hashAlgo;
+}
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/IdentityDTO.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/IdentityDTO.java
new file mode 100644
index 0000000000..9cfa0aae25
--- /dev/null
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/spi/IdentityDTO.java
@@ -0,0 +1,75 @@
+/* ====================================================================
+ 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.
+==================================================================== */
+
+/* ====================================================================
+ This product contains an ASLv2 licensed version of the OOXML signer
+ package from the eID Applet project
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ Copyright (C) 2008-2014 FedICT.
+ ================================================================= */
+
+package org.apache.poi.poifs.crypt.dsig.spi;
+
+import java.io.Serializable;
+import java.util.GregorianCalendar;
+
+/**
+ * Identity Data Transfer Object.
+ *
+ * @author Frank Cornelis
+ *
+ */
+public class IdentityDTO implements Serializable {
+
+ /*
+ * We implement serializable to allow this class to be used in distributed
+ * containers as defined in the Servlet v2.4 specification.
+ */
+ private static final long serialVersionUID = 1L;
+
+ public String cardNumber;
+
+ public String chipNumber;
+
+ public GregorianCalendar cardValidityDateBegin;
+
+ public GregorianCalendar cardValidityDateEnd;
+
+ public String cardDeliveryMunicipality;
+
+ public String nationalNumber;
+
+ public String name;
+
+ public String firstName;
+
+ public String middleName;
+
+ public String nationality;
+
+ public String placeOfBirth;
+
+ public GregorianCalendar dateOfBirth;
+
+ public boolean male;
+
+ public boolean female;
+
+ public String nobleCondition;
+
+ public String duplicate;
+}
\ No newline at end of file
diff --git a/src/ooxml/java/org/apache/poi/util/MethodUtils.java b/src/ooxml/java/org/apache/poi/util/MethodUtils.java
new file mode 100644
index 0000000000..c006c85462
--- /dev/null
+++ b/src/ooxml/java/org/apache/poi/util/MethodUtils.java
@@ -0,0 +1,1334 @@
+/* ====================================================================
+ 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.util;
+
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+
+/**
+ * Utility reflection methods focussed on methods in general rather than properties in particular.
+ *
+ * Known Limitations
+ * Accessing Public Methods In A Default Access Superclass
+ * There is an issue when invoking public methods contained in a default access superclass.
+ * Reflection locates these methods fine and correctly assigns them as public.
+ * However, an IllegalAccessException is thrown if the method is invoked.
+ *
+ * MethodUtils contains a workaround for this situation.
+ * It will attempt to call setAccessible on this method.
+ * If this call succeeds, then the method can be invoked as normal.
+ * This call will only succeed when the application has sufficient security privilages.
+ * If this call fails then a warning will be logged and the method may fail.
+ *
+ * @author Craig R. McClanahan
+ * @author Ralph Schaer
+ * @author Chris Audley
+ * @author Rey François
+ * @author Gregor Raýman
+ * @author Jan Sorensen
+ * @author Robert Burrell Donkin
+ */
+
+public class MethodUtils {
+
+ // --------------------------------------------------------- Private Methods
+
+ /**
+ * Only log warning about accessibility work around once.
+ *
+ * Note that this is broken when this class is deployed via a shared
+ * classloader in a container, as the warning message will be emitted
+ * only once, not once per webapp. However making the warning appear
+ * once per webapp means having a map keyed by context classloader
+ * which introduces nasty memory-leak problems. As this warning is
+ * really optional we can ignore this problem; only one of the webapps
+ * will get the warning in its logs but that should be good enough.
+ */
+ private static boolean loggedAccessibleWarning = false;
+
+ /**
+ * Indicates whether methods should be cached for improved performance.
+ *
+ * Note that when this class is deployed via a shared classloader in
+ * a container, this will affect all webapps. However making this
+ * configurable per webapp would mean having a map keyed by context classloader
+ * which may introduce memory-leak problems.
+ */
+ private static boolean CACHE_METHODS = true;
+
+ /** An empty class array */
+ private static final Class[] EMPTY_CLASS_PARAMETERS = new Class[0];
+ /** An empty object array */
+ private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
+
+ // --------------------------------------------------------- Public Methods
+
+ /**
+ *
Invoke a named method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than invokeExactMethod().
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeMethod(Object object,String methodName,Object [] args)}.
+ *
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param arg use this argument
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeMethod(
+ Object object,
+ String methodName,
+ Object arg)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ Object[] args = {arg};
+ return invokeMethod(object, methodName, args);
+
+ }
+
+
+ /**
+ * Invoke a named method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
+ *
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeMethod(
+ Object object,
+ String methodName,
+ Object[] args)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+ int arguments = args.length;
+ Class[] parameterTypes = new Class[arguments];
+ for (int i = 0; i < arguments; i++) {
+ parameterTypes[i] = args[i].getClass();
+ }
+ return invokeMethod(object, methodName, args, parameterTypes);
+
+ }
+
+
+ /**
+ * Invoke a named method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than {@link
+ * #invokeExactMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @param parameterTypes match these parameters - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeMethod(
+ Object object,
+ String methodName,
+ Object[] args,
+ Class[] parameterTypes)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (parameterTypes == null) {
+ parameterTypes = EMPTY_CLASS_PARAMETERS;
+ }
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+
+ Method method = getMatchingAccessibleMethod(
+ object.getClass(),
+ methodName,
+ parameterTypes);
+ if (method == null) {
+ throw new NoSuchMethodException("No such accessible method: " +
+ methodName + "() on object: " + object.getClass().getName());
+ }
+ return method.invoke(object, args);
+ }
+
+
+ /**
+ * Invoke a method whose parameter type matches exactly the object
+ * type.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
+ *
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param arg use this argument
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactMethod(
+ Object object,
+ String methodName,
+ Object arg)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ Object[] args = {arg};
+ return invokeExactMethod(object, methodName, args);
+
+ }
+
+
+ /**
+ * Invoke a method whose parameter types match exactly the object
+ * types.
+ *
+ * This uses reflection to invoke the method obtained from a call to
+ * getAccessibleMethod().
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactMethod(
+ Object object,
+ String methodName,
+ Object[] args)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+ int arguments = args.length;
+ Class[] parameterTypes = new Class[arguments];
+ for (int i = 0; i < arguments; i++) {
+ parameterTypes[i] = args[i].getClass();
+ }
+ return invokeExactMethod(object, methodName, args, parameterTypes);
+
+ }
+
+
+ /**
+ * Invoke a method whose parameter types match exactly the parameter
+ * types given.
+ *
+ * This uses reflection to invoke the method obtained from a call to
+ * getAccessibleMethod().
+ *
+ * @param object invoke method on this object
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @param parameterTypes match these parameters - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactMethod(
+ Object object,
+ String methodName,
+ Object[] args,
+ Class[] parameterTypes)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+
+ if (parameterTypes == null) {
+ parameterTypes = EMPTY_CLASS_PARAMETERS;
+ }
+
+ Method method = getAccessibleMethod(
+ object.getClass(),
+ methodName,
+ parameterTypes);
+ if (method == null) {
+ throw new NoSuchMethodException("No such accessible method: " +
+ methodName + "() on object: " + object.getClass().getName());
+ }
+ return method.invoke(object, args);
+
+ }
+
+ /**
+ * Invoke a static method whose parameter types match exactly the parameter
+ * types given.
+ *
+ * This uses reflection to invoke the method obtained from a call to
+ * {@link #getAccessibleMethod(Class, String, Class[])}.
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @param parameterTypes match these parameters - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object[] args,
+ Class[] parameterTypes)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+
+ if (parameterTypes == null) {
+ parameterTypes = EMPTY_CLASS_PARAMETERS;
+ }
+
+ Method method = getAccessibleMethod(
+ objectClass,
+ methodName,
+ parameterTypes);
+ if (method == null) {
+ throw new NoSuchMethodException("No such accessible method: " +
+ methodName + "() on class: " + objectClass.getName());
+ }
+ return method.invoke(null, args);
+
+ }
+
+ /**
+ * Invoke a named static method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than {@link #invokeExactMethod(Object, String, Object[], Class[])}.
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args)}.
+ *
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param arg use this argument
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object arg)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ Object[] args = {arg};
+ return invokeStaticMethod (objectClass, methodName, args);
+
+ }
+
+
+ /**
+ * Invoke a named static method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than {@link #invokeExactMethod(Object object,String methodName,Object [] args)}.
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}.
+ *
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object[] args)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+ int arguments = args.length;
+ Class[] parameterTypes = new Class[arguments];
+ for (int i = 0; i < arguments; i++) {
+ parameterTypes[i] = args[i].getClass();
+ }
+ return invokeStaticMethod (objectClass, methodName, args, parameterTypes);
+
+ }
+
+
+ /**
+ * Invoke a named static method whose parameter type matches the object type.
+ *
+ * The behaviour of this method is less deterministic
+ * than {@link
+ * #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}.
+ * It loops through all methods with names that match
+ * and then executes the first it finds with compatable parameters.
+ *
+ * This method supports calls to methods taking primitive parameters
+ * via passing in wrapping classes. So, for example, a Boolean class
+ * would match a boolean primitive.
+ *
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @param parameterTypes match these parameters - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object[] args,
+ Class[] parameterTypes)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ if (parameterTypes == null) {
+ parameterTypes = EMPTY_CLASS_PARAMETERS;
+ }
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+
+ Method method = getMatchingAccessibleMethod(
+ objectClass,
+ methodName,
+ parameterTypes);
+ if (method == null) {
+ throw new NoSuchMethodException("No such accessible method: " +
+ methodName + "() on class: " + objectClass.getName());
+ }
+ return method.invoke(null, args);
+ }
+
+
+ /**
+ * Invoke a static method whose parameter type matches exactly the object
+ * type.
+ *
+ * This is a convenient wrapper for
+ * {@link #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args)}.
+ *
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param arg use this argument
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object arg)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+
+ Object[] args = {arg};
+ return invokeExactStaticMethod (objectClass, methodName, args);
+
+ }
+
+
+ /**
+ * Invoke a static method whose parameter types match exactly the object
+ * types.
+ *
+ * This uses reflection to invoke the method obtained from a call to
+ * {@link #getAccessibleMethod(Class, String, Class[])}.
+ *
+ * @param objectClass invoke static method on this class
+ * @param methodName get method with this name
+ * @param args use these arguments - treat null as empty array
+ * @return The value returned by the invoked method
+ *
+ * @throws NoSuchMethodException if there is no such accessible method
+ * @throws InvocationTargetException wraps an exception thrown by the
+ * method invoked
+ * @throws IllegalAccessException if the requested method is not accessible
+ * via reflection
+ */
+ public static Object invokeExactStaticMethod(
+ Class objectClass,
+ String methodName,
+ Object[] args)
+ throws
+ NoSuchMethodException,
+ IllegalAccessException,
+ InvocationTargetException {
+ if (args == null) {
+ args = EMPTY_OBJECT_ARRAY;
+ }
+ int arguments = args.length;
+ Class[] parameterTypes = new Class[arguments];
+ for (int i = 0; i < arguments; i++) {
+ parameterTypes[i] = args[i].getClass();
+ }
+ return invokeExactStaticMethod(objectClass, methodName, args, parameterTypes);
+
+ }
+
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) with given name and a single parameter. If no such method
+ * can be found, return null.
+ * Basically, a convenience wrapper that constructs a Class
+ * array for you.
+ *
+ * @param clazz get method from this class
+ * @param methodName get method with this name
+ * @param parameterType taking this type of parameter
+ * @return The accessible method
+ */
+ public static Method getAccessibleMethod(
+ Class clazz,
+ String methodName,
+ Class parameterType) {
+
+ Class[] parameterTypes = {parameterType};
+ return getAccessibleMethod(clazz, methodName, parameterTypes);
+
+ }
+
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) with given name and parameters. If no such method
+ * can be found, return null.
+ * This is just a convenient wrapper for
+ * {@link #getAccessibleMethod(Method method)}.
+ *
+ * @param clazz get method from this class
+ * @param methodName get method with this name
+ * @param parameterTypes with these parameters types
+ * @return The accessible method
+ */
+ public static Method getAccessibleMethod(
+ Class clazz,
+ String methodName,
+ Class[] parameterTypes) {
+
+ try {
+ MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, true);
+ Method method = getAccessibleMethod
+ (clazz, clazz.getMethod(methodName, parameterTypes));
+ return method;
+ } catch (NoSuchMethodException e) {
+ return (null);
+ }
+
+ }
+
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) that implements the specified Method. If no such method
+ * can be found, return null.
+ *
+ * @param method The method that we wish to call
+ * @return The accessible method
+ */
+ public static Method getAccessibleMethod(Method method) {
+
+ // Make sure we have a method to check
+ if (method == null) {
+ return (null);
+ }
+
+ return getAccessibleMethod(method.getDeclaringClass(), method);
+
+ }
+
+
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) that implements the specified Method. If no such method
+ * can be found, return null.
+ *
+ * @param clazz The class of the object
+ * @param method The method that we wish to call
+ * @return The accessible method
+ */
+ public static Method getAccessibleMethod(Class clazz, Method method) {
+
+ // Make sure we have a method to check
+ if (method == null) {
+ return (null);
+ }
+
+ // If the requested method is not public we cannot call it
+ if (!Modifier.isPublic(method.getModifiers())) {
+ return (null);
+ }
+
+ boolean sameClass = true;
+ if (clazz == null) {
+ clazz = method.getDeclaringClass();
+ } else {
+ sameClass = clazz.equals(method.getDeclaringClass());
+ if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
+ throw new IllegalArgumentException(clazz.getName() +
+ " is not assignable from " + method.getDeclaringClass().getName());
+ }
+ }
+
+ // If the class is public, we are done
+ if (Modifier.isPublic(clazz.getModifiers())) {
+ if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
+ setMethodAccessible(method); // Default access superclass workaround
+ }
+ return (method);
+ }
+
+ String methodName = method.getName();
+ Class[] parameterTypes = method.getParameterTypes();
+
+ // Check the implemented interfaces and subinterfaces
+ method =
+ getAccessibleMethodFromInterfaceNest(clazz,
+ methodName,
+ parameterTypes);
+
+ // Check the superclass chain
+ if (method == null) {
+ method = getAccessibleMethodFromSuperclass(clazz,
+ methodName,
+ parameterTypes);
+ }
+
+ return (method);
+
+ }
+
+
+ // -------------------------------------------------------- Private Methods
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) by scanning through the superclasses. If no such method
+ * can be found, return null.
+ *
+ * @param clazz Class to be checked
+ * @param methodName Method name of the method we wish to call
+ * @param parameterTypes The parameter type signatures
+ */
+ private static Method getAccessibleMethodFromSuperclass
+ (Class clazz, String methodName, Class[] parameterTypes) {
+
+ Class parentClazz = clazz.getSuperclass();
+ while (parentClazz != null) {
+ if (Modifier.isPublic(parentClazz.getModifiers())) {
+ try {
+ return parentClazz.getMethod(methodName, parameterTypes);
+ } catch (NoSuchMethodException e) {
+ return null;
+ }
+ }
+ parentClazz = parentClazz.getSuperclass();
+ }
+ return null;
+ }
+
+ /**
+ * Return an accessible method (that is, one that can be invoked via
+ * reflection) that implements the specified method, by scanning through
+ * all implemented interfaces and subinterfaces. If no such method
+ * can be found, return null.
+ *
+ * There isn't any good reason why this method must be private.
+ * It is because there doesn't seem any reason why other classes should
+ * call this rather than the higher level methods.
+ *
+ * @param clazz Parent class for the interfaces to be checked
+ * @param methodName Method name of the method we wish to call
+ * @param parameterTypes The parameter type signatures
+ */
+ private static Method getAccessibleMethodFromInterfaceNest
+ (Class clazz, String methodName, Class[] parameterTypes) {
+
+ Method method = null;
+
+ // Search up the superclass chain
+ for (; clazz != null; clazz = clazz.getSuperclass()) {
+
+ // Check the implemented interfaces of the parent class
+ Class[] interfaces = clazz.getInterfaces();
+ for (int i = 0; i < interfaces.length; i++) {
+
+ // Is this interface public?
+ if (!Modifier.isPublic(interfaces[i].getModifiers())) {
+ continue;
+ }
+
+ // Does the method exist on this interface?
+ try {
+ method = interfaces[i].getDeclaredMethod(methodName,
+ parameterTypes);
+ } catch (NoSuchMethodException e) {
+ /* Swallow, if no method is found after the loop then this
+ * method returns null.
+ */
+ }
+ if (method != null) {
+ return method;
+ }
+
+ // Recursively check our parent interfaces
+ method =
+ getAccessibleMethodFromInterfaceNest(interfaces[i],
+ methodName,
+ parameterTypes);
+ if (method != null) {
+ return method;
+ }
+
+ }
+
+ }
+
+ // If we found a method return it
+ if (method != null) {
+ return (method);
+ }
+
+ // We did not find anything
+ return (null);
+
+ }
+
+ /**
+ * Find an accessible method that matches the given name and has compatible parameters.
+ * Compatible parameters mean that every method parameter is assignable from
+ * the given parameters.
+ * In other words, it finds a method with the given name
+ * that will take the parameters given.
+ *
+ *
This method is slightly undeterminstic since it loops
+ * through methods names and return the first matching method.
+ *
+ * This method is used by
+ * {@link
+ * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
+ *
+ *
This method can match primitive parameter by passing in wrapper classes.
+ * For example, a Boolean will match a primitive boolean
+ * parameter.
+ *
+ * @param clazz find method in this class
+ * @param methodName find method with this name
+ * @param parameterTypes find method with compatible parameters
+ * @return The accessible method
+ */
+ public static Method getMatchingAccessibleMethod(
+ Class clazz,
+ String methodName,
+ Class[] parameterTypes) {
+ // trace logging
+ Log log = LogFactory.getLog(MethodUtils.class);
+ if (log.isTraceEnabled()) {
+ log.trace("Matching name=" + methodName + " on " + clazz);
+ }
+ MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);
+
+ // see if we can find the method directly
+ // most of the time this works and it's much faster
+ try {
+ Method method = clazz.getMethod(methodName, parameterTypes);
+ if (log.isTraceEnabled()) {
+ log.trace("Found straight match: " + method);
+ log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
+ }
+
+ setMethodAccessible(method); // Default access superclass workaround
+
+ return method;
+
+ } catch (NoSuchMethodException e) { /* SWALLOW */ }
+
+ // search through all methods
+ int paramSize = parameterTypes.length;
+ Method bestMatch = null;
+ Method[] methods = clazz.getMethods();
+ float bestMatchCost = Float.MAX_VALUE;
+ float myCost = Float.MAX_VALUE;
+ for (int i = 0, size = methods.length; i < size ; i++) {
+ if (methods[i].getName().equals(methodName)) {
+ // log some trace information
+ if (log.isTraceEnabled()) {
+ log.trace("Found matching name:");
+ log.trace(methods[i]);
+ }
+
+ // compare parameters
+ Class[] methodsParams = methods[i].getParameterTypes();
+ int methodParamSize = methodsParams.length;
+ if (methodParamSize == paramSize) {
+ boolean match = true;
+ for (int n = 0 ; n < methodParamSize; n++) {
+ if (log.isTraceEnabled()) {
+ log.trace("Param=" + parameterTypes[n].getName());
+ log.trace("Method=" + methodsParams[n].getName());
+ }
+ if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
+ if (log.isTraceEnabled()) {
+ log.trace(methodsParams[n] + " is not assignable from "
+ + parameterTypes[n]);
+ }
+ match = false;
+ break;
+ }
+ }
+
+ if (match) {
+ // get accessible version of method
+ Method method = getAccessibleMethod(clazz, methods[i]);
+ if (method != null) {
+ if (log.isTraceEnabled()) {
+ log.trace(method + " accessible version of "
+ + methods[i]);
+ }
+ setMethodAccessible(method); // Default access superclass workaround
+ myCost = getTotalTransformationCost(parameterTypes,method.getParameterTypes());
+ if ( myCost < bestMatchCost ) {
+ bestMatch = method;
+ bestMatchCost = myCost;
+ }
+ }
+
+ log.trace("Couldn't find accessible method.");
+ }
+ }
+ }
+ }
+ if ( bestMatch == null ){
+ // didn't find a match
+ log.trace("No match found.");
+ }
+
+ return bestMatch;
+ }
+
+ public static Constructor getMatchingAccessibleConstructor(
+ Class clazz,
+ Class[] parameterTypes) {
+ // trace logging
+ Log log = LogFactory.getLog(MethodUtils.class);
+ MethodDescriptor md = new MethodDescriptor(clazz, "dummy", parameterTypes, false);
+
+ // see if we can find the method directly
+ // most of the time this works and it's much faster
+ try {
+ Constructor constructor = clazz.getConstructor(parameterTypes);
+ if (log.isTraceEnabled()) {
+ log.trace("Found straight match: " + constructor);
+ log.trace("isPublic:" + Modifier.isPublic(constructor.getModifiers()));
+ }
+
+ setMethodAccessible(constructor); // Default access superclass workaround
+
+ return constructor;
+
+ } catch (NoSuchMethodException e) { /* SWALLOW */ }
+
+ // search through all methods
+ int paramSize = parameterTypes.length;
+ Constructor bestMatch = null;
+ Constructor>[] constructors = clazz.getConstructors();
+ float bestMatchCost = Float.MAX_VALUE;
+ float myCost = Float.MAX_VALUE;
+ for (int i = 0, size = constructors.length; i < size ; i++) {
+ // compare parameters
+ Class[] methodsParams = constructors[i].getParameterTypes();
+ int methodParamSize = methodsParams.length;
+ if (methodParamSize == paramSize) {
+ boolean match = true;
+ for (int n = 0 ; n < methodParamSize; n++) {
+ if (log.isTraceEnabled()) {
+ log.trace("Param=" + parameterTypes[n].getName());
+ log.trace("Method=" + methodsParams[n].getName());
+ }
+ if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
+ if (log.isTraceEnabled()) {
+ log.trace(methodsParams[n] + " is not assignable from "
+ + parameterTypes[n]);
+ }
+ match = false;
+ break;
+ }
+ }
+
+ if (match) {
+ // get accessible version of method
+ Constructor cons = (Constructor)constructors[i];
+ myCost = getTotalTransformationCost(parameterTypes,cons.getParameterTypes());
+ if ( myCost < bestMatchCost ) {
+ bestMatch = cons;
+ bestMatchCost = myCost;
+ }
+ }
+ }
+ }
+ if ( bestMatch == null ){
+ // didn't find a match
+ log.trace("No match found.");
+ }
+
+ return bestMatch;
+ }
+
+ /**
+ * Try to make the method accessible
+ * @param method The source arguments
+ */
+ private static void setMethodAccessible(Object method) {
+ try {
+ //
+ // XXX Default access superclass workaround
+ //
+ // When a public class has a default access superclass
+ // with public methods, these methods are accessible.
+ // Calling them from compiled code works fine.
+ //
+ // Unfortunately, using reflection to invoke these methods
+ // seems to (wrongly) to prevent access even when the method
+ // modifer is public.
+ //
+ // The following workaround solves the problem but will only
+ // work from sufficiently privilages code.
+ //
+ // Better workarounds would be greatfully accepted.
+ //
+ if (method instanceof Method) {
+ ((Method)method).setAccessible(true);
+ } else if (method instanceof Constructor) {
+ ((Constructor)method).setAccessible(true);
+ } else {
+ throw new RuntimeException("invalid parameter");
+ }
+
+ } catch (SecurityException se) {
+ // log but continue just in case the method.invoke works anyway
+ Log log = LogFactory.getLog(MethodUtils.class);
+ if (!loggedAccessibleWarning) {
+ boolean vulnerableJVM = false;
+ try {
+ String specVersion = System.getProperty("java.specification.version");
+ if (specVersion.charAt(0) == '1' &&
+ (specVersion.charAt(2) == '0' ||
+ specVersion.charAt(2) == '1' ||
+ specVersion.charAt(2) == '2' ||
+ specVersion.charAt(2) == '3')) {
+
+ vulnerableJVM = true;
+ }
+ } catch (SecurityException e) {
+ // don't know - so display warning
+ vulnerableJVM = true;
+ }
+ if (vulnerableJVM) {
+ log.warn(
+ "Current Security Manager restricts use of workarounds for reflection bugs "
+ + " in pre-1.4 JVMs.");
+ }
+ loggedAccessibleWarning = true;
+ }
+ log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
+ }
+ }
+
+ /**
+ * Returns the sum of the object transformation cost for each class in the source
+ * argument list.
+ * @param srcArgs The source arguments
+ * @param destArgs The destination arguments
+ * @return The total transformation cost
+ */
+ private static float getTotalTransformationCost(Class[] srcArgs, Class[] destArgs) {
+
+ float totalCost = 0.0f;
+ for (int i = 0; i < srcArgs.length; i++) {
+ Class srcClass, destClass;
+ srcClass = srcArgs[i];
+ destClass = destArgs[i];
+ totalCost += getObjectTransformationCost(srcClass, destClass);
+ }
+
+ return totalCost;
+ }
+
+ /**
+ * Gets the number of steps required needed to turn the source class into the
+ * destination class. This represents the number of steps in the object hierarchy
+ * graph.
+ * @param srcClass The source class
+ * @param destClass The destination class
+ * @return The cost of transforming an object
+ */
+ private static float getObjectTransformationCost(Class srcClass, Class destClass) {
+ float cost = 0.0f;
+ while (destClass != null && !destClass.equals(srcClass)) {
+ if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) {
+ // slight penalty for interface match.
+ // we still want an exact match to override an interface match, but
+ // an interface match should override anything where we have to get a
+ // superclass.
+ cost += 0.25f;
+ break;
+ }
+ cost++;
+ destClass = destClass.getSuperclass();
+ }
+
+ /*
+ * If the destination class is null, we've travelled all the way up to
+ * an Object match. We'll penalize this by adding 1.5 to the cost.
+ */
+ if (destClass == null) {
+ cost += 1.5f;
+ }
+
+ return cost;
+ }
+
+
+ /**
+ * Determine whether a type can be used as a parameter in a method invocation.
+ * This method handles primitive conversions correctly.
+ *
+ * In order words, it will match a Boolean to a boolean,
+ * a Long to a long,
+ * a Float to a float,
+ * a Integer to a int,
+ * and a Double to a double.
+ * Now logic widening matches are allowed.
+ * For example, a Long will not match a int.
+ *
+ * @param parameterType the type of parameter accepted by the method
+ * @param parameterization the type of parameter being tested
+ *
+ * @return true if the assignement is compatible.
+ */
+ public static final boolean isAssignmentCompatible(Class parameterType, Class parameterization) {
+ // try plain assignment
+ if (parameterType.isAssignableFrom(parameterization)) {
+ return true;
+ }
+
+ if (parameterType.isPrimitive()) {
+ // this method does *not* do widening - you must specify exactly
+ // is this the right behaviour?
+ Class parameterWrapperClazz = getPrimitiveWrapper(parameterType);
+ if (parameterWrapperClazz != null) {
+ return parameterWrapperClazz.equals(parameterization);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Gets the wrapper object class for the given primitive type class.
+ * For example, passing boolean.class returns Boolean.class
+ * @param primitiveType the primitive type class for which a match is to be found
+ * @return the wrapper type associated with the given primitive
+ * or null if no match is found
+ */
+ public static Class getPrimitiveWrapper(Class primitiveType) {
+ // does anyone know a better strategy than comparing names?
+ if (boolean.class.equals(primitiveType)) {
+ return Boolean.class;
+ } else if (float.class.equals(primitiveType)) {
+ return Float.class;
+ } else if (long.class.equals(primitiveType)) {
+ return Long.class;
+ } else if (int.class.equals(primitiveType)) {
+ return Integer.class;
+ } else if (short.class.equals(primitiveType)) {
+ return Short.class;
+ } else if (byte.class.equals(primitiveType)) {
+ return Byte.class;
+ } else if (double.class.equals(primitiveType)) {
+ return Double.class;
+ } else if (char.class.equals(primitiveType)) {
+ return Character.class;
+ } else {
+
+ return null;
+ }
+ }
+
+ /**
+ * Gets the class for the primitive type corresponding to the primitive wrapper class given.
+ * For example, an instance of Boolean.class returns a boolean.class.
+ * @param wrapperType the
+ * @return the primitive type class corresponding to the given wrapper class,
+ * null if no match is found
+ */
+ public static Class getPrimitiveType(Class wrapperType) {
+ // does anyone know a better strategy than comparing names?
+ if (Boolean.class.equals(wrapperType)) {
+ return boolean.class;
+ } else if (Float.class.equals(wrapperType)) {
+ return float.class;
+ } else if (Long.class.equals(wrapperType)) {
+ return long.class;
+ } else if (Integer.class.equals(wrapperType)) {
+ return int.class;
+ } else if (Short.class.equals(wrapperType)) {
+ return short.class;
+ } else if (Byte.class.equals(wrapperType)) {
+ return byte.class;
+ } else if (Double.class.equals(wrapperType)) {
+ return double.class;
+ } else if (Character.class.equals(wrapperType)) {
+ return char.class;
+ } else {
+ Log log = LogFactory.getLog(MethodUtils.class);
+ if (log.isDebugEnabled()) {
+ log.debug("Not a known primitive wrapper class: " + wrapperType);
+ }
+ return null;
+ }
+ }
+
+ /**
+ * Find a non primitive representation for given primitive class.
+ *
+ * @param clazz the class to find a representation for, not null
+ * @return the original class if it not a primitive. Otherwise the wrapper class. Not null
+ */
+ public static Class toNonPrimitiveClass(Class clazz) {
+ if (clazz.isPrimitive()) {
+ Class primitiveClazz = MethodUtils.getPrimitiveWrapper(clazz);
+ // the above method returns
+ if (primitiveClazz != null) {
+ return primitiveClazz;
+ } else {
+ return clazz;
+ }
+ } else {
+ return clazz;
+ }
+ }
+
+
+ /**
+ * Represents the key to looking up a Method by reflection.
+ */
+ private static class MethodDescriptor {
+ private Class cls;
+ private String methodName;
+ private Class[] paramTypes;
+ private boolean exact;
+ private int hashCode;
+
+ /**
+ * The sole constructor.
+ *
+ * @param cls the class to reflect, must not be null
+ * @param methodName the method name to obtain
+ * @param paramTypes the array of classes representing the paramater types
+ * @param exact whether the match has to be exact.
+ */
+ public MethodDescriptor(Class cls, String methodName, Class[] paramTypes, boolean exact) {
+ if (cls == null) {
+ throw new IllegalArgumentException("Class cannot be null");
+ }
+ if (methodName == null) {
+ throw new IllegalArgumentException("Method Name cannot be null");
+ }
+ if (paramTypes == null) {
+ paramTypes = EMPTY_CLASS_PARAMETERS;
+ }
+
+ this.cls = cls;
+ this.methodName = methodName;
+ this.paramTypes = paramTypes;
+ this.exact= exact;
+
+ this.hashCode = methodName.length();
+ }
+ /**
+ * Checks for equality.
+ * @param obj object to be tested for equality
+ * @return true, if the object describes the same Method.
+ */
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MethodDescriptor)) {
+ return false;
+ }
+ MethodDescriptor md = (MethodDescriptor)obj;
+
+ return (
+ exact == md.exact &&
+ methodName.equals(md.methodName) &&
+ cls.equals(md.cls) &&
+ java.util.Arrays.equals(paramTypes, md.paramTypes)
+ );
+ }
+ /**
+ * Returns the string length of method name. I.e. if the
+ * hashcodes are different, the objects are different. If the
+ * hashcodes are the same, need to use the equals method to
+ * determine equality.
+ * @return the string length of method name.
+ */
+ public int hashCode() {
+ return hashCode;
+ }
+ }
+}
diff --git a/src/ooxml/java/org/apache/poi/util/XmlSort.java b/src/ooxml/java/org/apache/poi/util/XmlSort.java
new file mode 100644
index 0000000000..4e1ffa54f0
--- /dev/null
+++ b/src/ooxml/java/org/apache/poi/util/XmlSort.java
@@ -0,0 +1,221 @@
+/* ====================================================================
+ 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.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Comparator;
+
+import javax.xml.namespace.QName;
+
+import org.apache.xmlbeans.XmlCursor;
+import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.XmlObject;
+
+/**
+ */
+public final class XmlSort
+{
+ /**
+ * Receives an XML element instance and sorts the children of this
+ * element in lexicographical (by default) order.
+ *
+ * @param args An array in which the first item is a
+ * path to the XML instance file and the second item (optional) is
+ * an XPath inside the document identifying the element to be sorted
+ */
+ public static void main(String[] args)
+ {
+ if (args.length < 1 || args.length > 2)
+ {
+ System.out.println(" java XmlSort []");
+ return;
+ }
+ File f = new File(args[0]);
+ try
+ {
+ XmlObject docInstance = XmlObject.Factory.parse(f);
+ XmlObject element = null;
+ if (args.length > 1)
+ {
+ String xpath = args[1];
+ XmlObject[] result = docInstance.selectPath(xpath);
+ if (result.length == 0)
+ {
+ System.out.println("ERROR: XPath \"" + xpath + "\" did not return any results");
+ }
+ else if (result.length > 1)
+ {
+ System.out.println("ERROR: XPath \"" + xpath + "\" returned more than one " +
+ "node (" + result.length + ")");
+ }
+ else
+ element = result[0];
+ }
+ else
+ {
+ // Navigate to the root element
+ XmlCursor c = docInstance.newCursor();
+ c.toFirstChild();
+ element = c.getObject();
+ c.dispose();
+ }
+ if (element != null)
+ sort(element, new QNameComparator(QNameComparator.ASCENDING));
+ System.out.println(docInstance.xmlText());
+ }
+ catch (IOException ioe)
+ {
+ System.out.println("ERROR: Could not open file: \"" + args[0] + "\": " +
+ ioe.getMessage());
+ }
+ catch (XmlException xe)
+ {
+ System.out.println("ERROR: Could not parse file: \"" + args[0] + "\": " +
+ xe.getMessage());
+ }
+ }
+
+ /**
+ * Sorts the children of element according to the order indicated by the
+ * comparator.
+ * @param element the element whose content is to be sorted. Only element children are sorted,
+ * attributes are not touched. When elements are reordered, all the text, comments and PIs
+ * follow the element that they come immediately after.
+ * @param comp a comparator that is to be used when comparing the QNames of two
+ * elements. See {@link org.apache.xmlbeans.samples.cursor.XmlSort.QNameComparator} for a simple
+ * implementation that compares two elements based on the value of their QName, but more
+ * complicated implementations are possible, for instance, ones that compare two elements based
+ * on the value of a specifc attribute etc.
+ * @throws IllegalArgumentException if the input XmlObject does not represent
+ * an element
+ */
+ public static void sort(XmlObject element, Comparator comp)
+ {
+ XmlCursor headCursor = element.newCursor();
+ if (!headCursor.isStart())
+ throw new IllegalStateException("The element parameter must point to a STARTDOC");
+ // We use insertion sort to minimize the number of swaps, because each swap means
+ // moving a part of the document
+ /* headCursor points to the beginning of the list of the already sorted items and
+ listCursor points to the beginning of the list of unsorted items
+ At the beginning, headCursor points to the first element and listCursor points to the
+ second element. The algorithm ends when listCursor cannot be moved to the "next"
+ element in the unsorted list, i.e. the unsorted list becomes empty */
+ boolean moved = headCursor.toFirstChild();
+ if (!moved)
+ {
+ // Cursor was not moved, which means that the given element has no children and
+ // therefore there is nothing to sort
+ return;
+ }
+ XmlCursor listCursor = headCursor.newCursor();
+ boolean moreElements = listCursor.toNextSibling();
+ while (moreElements)
+ {
+ moved = false;
+ // While we can move the head of the unsorted list, it means that there are still
+ // items (elements) that need to be sorted
+ while (headCursor.comparePosition(listCursor) < 0)
+ {
+ if (comp.compare(headCursor, listCursor) > 0)
+ {
+ // We have found the position in the sorted list, insert the element and the
+ // text following the element in the current position
+ /*
+ * Uncomment this code to cause the text before the element to move along
+ * with the element, rather than the text after the element. Notice that this
+ * is more difficult to do, because the cursor's "type" refers to the position
+ * to the right of the cursor, so to get the type of the token to the left, the
+ * cursor needs to be first moved to the left (previous token)
+ *
+ headCursor.toPrevToken();
+ while (headCursor.isComment() || headCursor.isProcinst() || headCursor.isText())
+ headCursor.toPrevToken();
+ headCursor.toNextToken();
+ listCursor.toPrevToken();
+ while (listCursor.isComment() || listCursor.isProcinst() || listCursor.isText())
+ listCursor.toPrevToken();
+ listCursor.toNextToken();
+ while (!listCursor.isStart())
+ listCursor.moveXml(headCursor);
+ listCursor.moveXml(headCursor);
+ */
+ // Move the element
+ listCursor.moveXml(headCursor);
+ // Move the text following the element
+ while (!listCursor.isStart() && !listCursor.isEnd())
+ listCursor.moveXml(headCursor);
+ moreElements = listCursor.isStart();
+ moved = true;
+ break;
+ }
+ headCursor.toNextSibling();
+ }
+ if (!moved)
+ {
+ // Because during the move of a fragment of XML, the listCursor is also moved, in
+ // case we didn't need to move XML (the new element to be inserted happened to
+ // be the last one in order), we need to move this cursor
+ moreElements = listCursor.toNextSibling();
+ }
+ // Reposition the head of the sorted list
+ headCursor.toParent();
+ headCursor.toFirstChild();
+ }
+ }
+
+ /**
+ * Implements a java.util.Comparator for comparing QNamevalues.
+ * The namespace URIs are compared first and if they are equal, the local parts are compared.
+ *
+ * The constructor accepts an argument indicating whether the comparison order is the same as
+ * the lexicographic order of the strings or the reverse.
+ */
+ public static final class QNameComparator implements Comparator
+ {
+ public static final int ASCENDING = 1;
+ public static final int DESCENDING = 2;
+
+ private int order;
+
+ public QNameComparator(int order)
+ {
+ this.order = order;
+ if (order != ASCENDING && order != DESCENDING)
+ throw new IllegalArgumentException("Please specify one of ASCENDING or DESCENDING "+
+ "comparison orders");
+ }
+
+ public int compare(Object o, Object o1)
+ {
+ XmlCursor cursor1 = (XmlCursor) o;
+ XmlCursor cursor2 = (XmlCursor) o1;
+ QName qname1 = cursor1.getName();
+ QName qname2 = cursor2.getName();
+ int qnameComparisonRes = qname1.getNamespaceURI().compareTo(qname2.getNamespaceURI());
+ if (qnameComparisonRes == 0)
+ return order == ASCENDING ?
+ qname1.getLocalPart().compareTo(qname2.getLocalPart()) :
+ -qname1.getLocalPart().compareTo(qname2.getLocalPart());
+ else
+ return order == ASCENDING ? qnameComparisonRes : -qnameComparisonRes;
+ }
+ }
+}
+
\ No newline at end of file
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd
new file mode 100644
index 0000000000..f7019f13f5
--- /dev/null
+++ b/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd
@@ -0,0 +1,103 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java
new file mode 100644
index 0000000000..afd70f08e5
--- /dev/null
+++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java
@@ -0,0 +1,317 @@
+/* ====================================================================
+ 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;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.cert.CRLException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509CRL;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.RSAKeyGenParameterSpec;
+import java.util.Date;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.bouncycastle.asn1.DERIA5String;
+import org.bouncycastle.asn1.DEROctetString;
+import org.bouncycastle.asn1.DERSequence;
+import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.AuthorityInformationAccess;
+import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.CRLNumber;
+import org.bouncycastle.asn1.x509.CRLReason;
+import org.bouncycastle.asn1.x509.DistributionPoint;
+import org.bouncycastle.asn1.x509.DistributionPointName;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.Extensions;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
+import org.bouncycastle.cert.X509CRLHolder;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.X509ExtensionUtils;
+import org.bouncycastle.cert.X509v2CRLBuilder;
+import org.bouncycastle.cert.X509v3CertificateBuilder;
+import org.bouncycastle.cert.jcajce.JcaX509CRLConverter;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.ocsp.BasicOCSPResp;
+import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder;
+import org.bouncycastle.cert.ocsp.CertificateID;
+import org.bouncycastle.cert.ocsp.CertificateStatus;
+import org.bouncycastle.cert.ocsp.OCSPReq;
+import org.bouncycastle.cert.ocsp.OCSPReqBuilder;
+import org.bouncycastle.cert.ocsp.OCSPResp;
+import org.bouncycastle.cert.ocsp.OCSPRespBuilder;
+import org.bouncycastle.cert.ocsp.Req;
+import org.bouncycastle.cert.ocsp.RevokedStatus;
+import org.bouncycastle.crypto.params.RSAKeyParameters;
+import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.DigestCalculator;
+import org.bouncycastle.operator.OperatorCreationException;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+public class PkiTestUtils {
+
+ private PkiTestUtils() {
+ super();
+ }
+
+ static KeyPair generateKeyPair() throws Exception {
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+ SecureRandom random = new SecureRandom();
+ keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024,
+ RSAKeyGenParameterSpec.F4), random);
+ KeyPair keyPair = keyPairGenerator.generateKeyPair();
+ return keyPair;
+ }
+
+ static X509Certificate generateCertificate(PublicKey subjectPublicKey,
+ String subjectDn, Date notBefore, Date notAfter,
+ X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
+ boolean caFlag, int pathLength, String crlUri, String ocspUri,
+ KeyUsage keyUsage)
+ throws IOException, OperatorCreationException, CertificateException
+ {
+ String signatureAlgorithm = "SHA1withRSA";
+ X500Name issuerName;
+ if (issuerCertificate != null) {
+ issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
+ } else {
+ issuerName = new X500Name(subjectDn);
+ }
+
+ RSAPublicKey rsaPubKey = (RSAPublicKey)subjectPublicKey;
+ RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent());
+
+ SubjectPublicKeyInfo subjectPublicKeyInfo =
+ SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);
+
+ DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder()
+ .setProvider("BC").build().get(CertificateID.HASH_SHA1);
+
+ X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(
+ issuerName
+ , new BigInteger(128, new SecureRandom())
+ , notBefore
+ , notAfter
+ , new X500Name(subjectDn)
+ , subjectPublicKeyInfo
+ );
+
+ X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
+ SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
+ AuthorityKeyIdentifier autKeyId = (issuerCertificate != null)
+ ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded()))
+ : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);
+
+ certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
+ certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);
+
+ if (caFlag) {
+ BasicConstraints bc;
+
+ if (-1 == pathLength) {
+ bc = new BasicConstraints(true);
+ } else {
+ bc = new BasicConstraints(pathLength);
+ }
+ certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
+ }
+
+ if (null != crlUri) {
+ int uri = GeneralName.uniformResourceIdentifier;
+ DERIA5String crlUriDer = new DERIA5String(crlUri);
+ GeneralName gn = new GeneralName(uri, crlUriDer);
+
+ DERSequence gnDer = new DERSequence(gn);
+ GeneralNames gns = GeneralNames.getInstance(gnDer);
+
+ DistributionPointName dpn = new DistributionPointName(0, gns);
+ DistributionPoint distp = new DistributionPoint(dpn, null, null);
+ DERSequence distpDer = new DERSequence(distp);
+ certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
+ }
+
+ if (null != ocspUri) {
+ int uri = GeneralName.uniformResourceIdentifier;
+ GeneralName ocspName = new GeneralName(uri, ocspUri);
+
+ AuthorityInformationAccess authorityInformationAccess =
+ new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspName);
+
+ certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
+ }
+
+ if (null != keyUsage) {
+ certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
+ }
+
+ JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
+ signerBuilder.setProvider("BC");
+
+ X509CertificateHolder certHolder =
+ certificateGenerator.build(signerBuilder.build(issuerPrivateKey));
+
+ /*
+ * Next certificate factory trick is needed to make sure that the
+ * certificate delivered to the caller is provided by the default
+ * security provider instead of BouncyCastle. If we don't do this trick
+ * we might run into trouble when trying to use the CertPath validator.
+ */
+// CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+// certificate = (X509Certificate) certificateFactory
+// .generateCertificate(new ByteArrayInputStream(certificate
+// .getEncoded()));
+ return new JcaX509CertificateConverter().getCertificate(certHolder);
+ }
+
+ static Document loadDocument(InputStream documentInputStream)
+ throws ParserConfigurationException, SAXException, IOException {
+ InputSource inputSource = new InputSource(documentInputStream);
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
+ .newInstance();
+ documentBuilderFactory.setNamespaceAware(true);
+ DocumentBuilder documentBuilder = documentBuilderFactory
+ .newDocumentBuilder();
+ Document document = documentBuilder.parse(inputSource);
+ return document;
+ }
+
+ static String toString(Node dom) throws TransformerException {
+ Source source = new DOMSource(dom);
+ StringWriter stringWriter = new StringWriter();
+ Result result = new StreamResult(stringWriter);
+ TransformerFactory transformerFactory = TransformerFactory
+ .newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ /*
+ * We have to omit the ?xml declaration if we want to embed the
+ * document.
+ */
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ transformer.transform(source, result);
+ return stringWriter.getBuffer().toString();
+ }
+
+ public static X509CRL generateCrl(X509Certificate issuer, PrivateKey issuerPrivateKey)
+ throws CertificateEncodingException, IOException, CRLException, OperatorCreationException {
+
+ X509CertificateHolder holder = new X509CertificateHolder(issuer.getEncoded());
+ X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(holder.getIssuer(), new Date());
+ crlBuilder.setNextUpdate(new Date(new Date().getTime() + 100000));
+ JcaContentSignerBuilder contentBuilder = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC");
+
+ CRLNumber crlNumber = new CRLNumber(new BigInteger("1234"));
+
+ crlBuilder.addExtension(Extension.cRLNumber, false, crlNumber);
+ X509CRLHolder x509Crl = crlBuilder.build(contentBuilder.build(issuerPrivateKey));
+ return new JcaX509CRLConverter().setProvider("BC").getCRL(x509Crl);
+ }
+
+ public static OCSPResp createOcspResp(X509Certificate certificate,
+ boolean revoked, X509Certificate issuerCertificate,
+ X509Certificate ocspResponderCertificate,
+ PrivateKey ocspResponderPrivateKey, String signatureAlgorithm,
+ long nonceTimeinMillis)
+ throws Exception {
+ DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder()
+ .setProvider("BC").build().get(CertificateID.HASH_SHA1);
+ X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
+ CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
+
+ // request
+ //create a nonce to avoid replay attack
+ BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
+ DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
+ Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
+ Extensions exts = new Extensions(ext);
+
+ OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
+ ocspReqBuilder.addRequest(certId);
+ ocspReqBuilder.setRequestExtensions(exts);
+ OCSPReq ocspReq = ocspReqBuilder.build();
+
+
+ SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo
+ (CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
+
+ BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
+ basicOCSPRespBuilder.setResponseExtensions(exts);
+
+ // request processing
+ Req[] requestList = ocspReq.getRequestList();
+ for (Req ocspRequest : requestList) {
+ CertificateID certificateID = ocspRequest.getCertID();
+ CertificateStatus certificateStatus = CertificateStatus.GOOD;
+ if (revoked) {
+ certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
+ }
+ basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
+ }
+
+ // basic response generation
+ X509CertificateHolder[] chain = null;
+ if (!ocspResponderCertificate.equals(issuerCertificate)) {
+ // TODO: HorribleProxy can't convert array input params yet
+ chain = new X509CertificateHolder[] {
+ new X509CertificateHolder(ocspResponderCertificate.getEncoded()),
+ issuerHolder
+ };
+ }
+
+ ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA")
+ .setProvider("BC").build(ocspResponderPrivateKey);
+ BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
+
+
+ OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
+ OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
+
+ return ocspResp;
+ }
+}
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java
new file mode 100644
index 0000000000..4444abe89d
--- /dev/null
+++ b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java
@@ -0,0 +1,544 @@
+/* ====================================================================
+ 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.
+==================================================================== */
+
+/* ====================================================================
+ This product contains an ASLv2 licensed version of the OOXML signer
+ package from the eID Applet project
+ http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
+ Copyright (C) 2008-2014 FedICT.
+ ================================================================= */
+package org.apache.poi.poifs.crypt;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.Key;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509CRL;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.apache.poi.POIDataSamples;
+import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.opc.PackageAccess;
+import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
+import org.apache.poi.poifs.crypt.dsig.SignatureInfo;
+import org.apache.poi.poifs.crypt.dsig.SignatureInfo.SignaturePart;
+import org.apache.poi.poifs.crypt.dsig.facets.EnvelopedSignatureFacet;
+import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet;
+import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet;
+import org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet;
+import org.apache.poi.poifs.crypt.dsig.services.RevocationData;
+import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService;
+import org.apache.poi.poifs.crypt.dsig.services.TimeStampService;
+import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator;
+import org.apache.poi.poifs.crypt.dsig.spi.DigestInfo;
+import org.apache.poi.util.DocumentHelper;
+import org.apache.poi.util.IOUtils;
+import org.apache.poi.util.POILogFactory;
+import org.apache.poi.util.POILogger;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.xmlbeans.XmlObject;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.cert.ocsp.OCSPResp;
+import org.etsi.uri.x01903.v13.DigestAlgAndValueType;
+import org.etsi.uri.x01903.v13.QualifyingPropertiesType;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.w3.x2000.x09.xmldsig.ReferenceType;
+import org.w3.x2000.x09.xmldsig.SignatureDocument;
+import org.w3c.dom.Document;
+
+public class TestSignatureInfo {
+ private static final POILogger LOG = POILogFactory.getLogger(TestSignatureInfo.class);
+ private static final POIDataSamples testdata = POIDataSamples.getXmlDSignInstance();
+
+ private static Calendar cal;
+ private KeyPair keyPair = null;
+ private X509Certificate x509 = null;
+
+
+
+ @BeforeClass
+ public static void initBouncy() throws MalformedURLException {
+ File bcProvJar = new File("lib/bcprov-ext-jdk15on-1.51.jar");
+ File bcPkixJar = new File("lib/bcpkix-jdk15on-151.jar");
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ URLClassLoader ucl = new URLClassLoader(new URL[]{bcProvJar.toURI().toURL(),bcPkixJar.toURI().toURL()}, cl);
+ Thread.currentThread().setContextClassLoader(ucl);
+ CryptoFunctions.registerBouncyCastle();
+
+ /*** TODO : set cal to now ... only set to fixed date for debugging ... */
+ cal = Calendar.getInstance();
+ cal.clear();
+ cal.setTimeZone(TimeZone.getTimeZone("UTC"));
+ cal.set(2014, 7, 6, 21, 42, 12);
+ }
+
+ @Test
+ public void getSignerUnsigned() throws Exception {
+ String testFiles[] = {
+ "hello-world-unsigned.docx",
+ "hello-world-unsigned.pptx",
+ "hello-world-unsigned.xlsx",
+ "hello-world-office-2010-technical-preview-unsigned.docx"
+ };
+
+ for (String testFile : testFiles) {
+ OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ);
+ SignatureConfig sic = new SignatureConfig();
+ sic.setOpcPackage(pkg);
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(sic);
+ List result = new ArrayList();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
+ }
+ }
+ pkg.revert();
+ pkg.close();
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+ }
+ }
+
+ @Test
+ public void getSigner() throws Exception {
+ String testFiles[] = {
+ "hyperlink-example-signed.docx",
+ "hello-world-signed.docx",
+ "hello-world-signed.pptx",
+ "hello-world-signed.xlsx",
+ "hello-world-office-2010-technical-preview.docx",
+ "ms-office-2010-signed.docx",
+ "ms-office-2010-signed.pptx",
+ "ms-office-2010-signed.xlsx",
+ "Office2010-SP1-XAdES-X-L.docx",
+ "signed.docx",
+ };
+
+ for (String testFile : testFiles) {
+ OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ);
+ SignatureConfig sic = new SignatureConfig();
+ sic.setOpcPackage(pkg);
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(sic);
+ List result = new ArrayList();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
+ }
+ }
+
+ assertNotNull(result);
+ assertEquals("test-file: "+testFile, 1, result.size());
+ X509Certificate signer = result.get(0);
+ LOG.log(POILogger.DEBUG, "signer: " + signer.getSubjectX500Principal());
+
+ boolean b = si.verifySignature();
+ assertTrue("test-file: "+testFile, b);
+ pkg.revert();
+ }
+ }
+
+ @Test
+ public void getMultiSigners() throws Exception {
+ String testFile = "hello-world-signed-twice.docx";
+ OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ);
+ SignatureConfig sic = new SignatureConfig();
+ sic.setOpcPackage(pkg);
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(sic);
+ List result = new ArrayList();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
+ }
+ }
+
+ assertNotNull(result);
+ assertEquals("test-file: "+testFile, 2, result.size());
+ X509Certificate signer1 = result.get(0);
+ X509Certificate signer2 = result.get(1);
+ LOG.log(POILogger.DEBUG, "signer 1: " + signer1.getSubjectX500Principal());
+ LOG.log(POILogger.DEBUG, "signer 2: " + signer2.getSubjectX500Principal());
+
+ boolean b = si.verifySignature();
+ assertTrue("test-file: "+testFile, b);
+ pkg.revert();
+ }
+
+ @Test
+ public void testSignSpreadsheet() throws Exception {
+ String testFile = "hello-world-unsigned.xlsx";
+ OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
+ sign(pkg, "Test", "CN=Test", 1);
+ pkg.close();
+ }
+
+ @Test
+ public void testManipulation() throws Exception {
+ // sign & validate
+ String testFile = "hello-world-unsigned.xlsx";
+ OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
+ sign(pkg, "Test", "CN=Test", 1);
+
+ // manipulate
+ XSSFWorkbook wb = new XSSFWorkbook(pkg);
+ wb.setSheetName(0, "manipulated");
+ // ... I don't know, why commit is protected ...
+ Method m = XSSFWorkbook.class.getDeclaredMethod("commit");
+ m.setAccessible(true);
+ m.invoke(wb);
+
+ // todo: test a manipulation on a package part, which is not signed
+ // ... maybe in combination with #56164
+
+ // validate
+ SignatureConfig sic = new SignatureConfig();
+ sic.setOpcPackage(pkg);
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(sic);
+ boolean b = si.verifySignature();
+ assertFalse("signature should be broken", b);
+
+ wb.close();
+ }
+
+ @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 result = new ArrayList();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
+ }
+ }
+ assertEquals(1, result.size());
+ pkg.close();
+ }
+
+ @Test
+ public void testSignEnvelopingDocument() throws Exception {
+ String testFile = "hello-world-unsigned.xlsx";
+ OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
+
+ initKeyPair("Test", "CN=Test");
+ final X509CRL crl = PkiTestUtils.generateCrl(x509, keyPair.getPrivate());
+
+ // setup
+ SignatureConfig signatureConfig = new SignatureConfig();
+ signatureConfig.setOpcPackage(pkg);
+ signatureConfig.setKey(keyPair.getPrivate());
+
+ /*
+ * We need at least 2 certificates for the XAdES-C complete certificate
+ * refs construction.
+ */
+ List certificateChain = new ArrayList();
+ certificateChain.add(x509);
+ certificateChain.add(x509);
+ signatureConfig.setSigningCertificateChain(certificateChain);
+
+ signatureConfig.addSignatureFacet(new EnvelopedSignatureFacet());
+ signatureConfig.addSignatureFacet(new KeyInfoSignatureFacet());
+ signatureConfig.addSignatureFacet(new XAdESSignatureFacet());
+ signatureConfig.addSignatureFacet(new XAdESXLSignatureFacet());
+
+ boolean mockTsp = false;
+ // http://timestamping.edelweb.fr/service/tsp
+ // http://tsa.belgium.be/connect
+ signatureConfig.setTspUrl("http://timestamping.edelweb.fr/service/tsp");
+ signatureConfig.setTspOldProtocol(true);
+
+ if (mockTsp) {
+ TimeStampService tspService = new TimeStampService(){
+ public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
+ revocationData.addCRL(crl);
+ return "time-stamp-token".getBytes();
+ }
+ public void setSignatureConfig(SignatureConfig config) {}
+ };
+ signatureConfig.setTspService(tspService);
+ } else {
+ TimeStampServiceValidator tspValidator = new TimeStampServiceValidator() {
+ @Override
+ public void validate(List certificateChain,
+ RevocationData revocationData) throws Exception {
+ for (X509Certificate certificate : certificateChain) {
+ LOG.log(POILogger.DEBUG, "certificate: " + certificate.getSubjectX500Principal());
+ LOG.log(POILogger.DEBUG, "validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter());
+ }
+ }
+ };
+ signatureConfig.setTspValidator(tspValidator);
+ signatureConfig.setTspOldProtocol(signatureConfig.getTspUrl().contains("edelweb"));
+ }
+
+ final RevocationData revocationData = new RevocationData();
+ revocationData.addCRL(crl);
+ OCSPResp ocspResp = PkiTestUtils.createOcspResp(x509, false,
+ x509, x509, keyPair.getPrivate(), "SHA1withRSA", cal.getTimeInMillis());
+ revocationData.addOCSP(ocspResp.getEncoded());
+
+ RevocationDataService revocationDataService = new RevocationDataService(){
+ public RevocationData getRevocationData(List certificateChain) {
+ return revocationData;
+ }
+ };
+ signatureConfig.setRevocationDataService(revocationDataService);
+
+ // operate
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(signatureConfig);
+ si.confirmSignature();
+
+ // verify
+ Iterator spIter = si.getSignatureParts().iterator();
+ assertTrue(spIter.hasNext());
+ SignaturePart sp = spIter.next();
+ boolean valid = sp.validate();
+ assertTrue(valid);
+
+ SignatureDocument sigDoc = sp.getSignatureDocument();
+ String declareNS =
+ "declare namespace xades='http://uri.etsi.org/01903/v1.3.2#'; "
+ + "declare namespace ds='http://www.w3.org/2000/09/xmldsig#'; ";
+
+ String digestValXQuery = declareNS +
+ "$this/ds:Signature/ds:SignedInfo/ds:Reference";
+ for (ReferenceType rt : (ReferenceType[])sigDoc.selectPath(digestValXQuery)) {
+ assertNotNull(rt.getDigestValue());
+ assertEquals(signatureConfig.getDigestMethodUri(), rt.getDigestMethod().getAlgorithm());
+ }
+
+ String certDigestXQuery = declareNS +
+ "$this//xades:SigningCertificate/xades:Cert/xades:CertDigest";
+ XmlObject xoList[] = sigDoc.selectPath(certDigestXQuery);
+ assertEquals(xoList.length, 1);
+ DigestAlgAndValueType certDigest = (DigestAlgAndValueType)xoList[0];
+ assertNotNull(certDigest.getDigestValue());
+
+ String qualPropXQuery = declareNS +
+ "$this/ds:Signature/ds:Object/xades:QualifyingProperties";
+ xoList = sigDoc.selectPath(qualPropXQuery);
+ assertEquals(xoList.length, 1);
+ QualifyingPropertiesType qualProp = (QualifyingPropertiesType)xoList[0];
+ boolean qualPropXsdOk = qualProp.validate();
+ assertTrue(qualPropXsdOk);
+
+ pkg.close();
+ }
+
+ @Test
+ public void testCertChain() throws Exception {
+ KeyStore keystore = KeyStore.getInstance("PKCS12");
+ String password = "test";
+ InputStream is = testdata.openResourceAsStream("chaintest.pfx");
+ keystore.load(is, password.toCharArray());
+ is.close();
+
+ Key key = keystore.getKey("poitest", password.toCharArray());
+ Certificate chainList[] = keystore.getCertificateChain("poitest");
+ List certChain = new ArrayList();
+ for (Certificate c : chainList) {
+ certChain.add((X509Certificate)c);
+ }
+ x509 = certChain.get(0);
+ keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key);
+
+ String testFile = "hello-world-unsigned.xlsx";
+ OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
+
+ SignatureConfig signatureConfig = new SignatureConfig();
+ signatureConfig.setKey(keyPair.getPrivate());
+ signatureConfig.setSigningCertificateChain(certChain);
+ Calendar cal = Calendar.getInstance();
+ cal.set(2007, 7, 1);
+ signatureConfig.setExecutionTime(cal.getTime());
+ signatureConfig.setDigestAlgo(HashAlgorithm.sha1);
+ signatureConfig.setOpcPackage(pkg);
+
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(signatureConfig);
+
+ si.confirmSignature();
+
+ for (SignaturePart sp : si.getSignatureParts()){
+ boolean b = sp.validate();
+ assertTrue(b);
+ X509Certificate signer = sp.getSigner();
+ assertNotNull("signer undefined?!", signer);
+ List certChainRes = sp.getCertChain();
+ assertEquals(3, certChainRes.size());
+ }
+
+ pkg.close();
+ }
+
+ @Test
+ public void testNonSha1() throws Exception {
+ String testFile = "hello-world-unsigned.xlsx";
+ initKeyPair("Test", "CN=Test");
+
+ SignatureConfig signatureConfig = new SignatureConfig();
+ signatureConfig.setKey(keyPair.getPrivate());
+ signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
+
+ HashAlgorithm testAlgo[] = { HashAlgorithm.sha224, HashAlgorithm.sha256
+ , HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.ripemd160 };
+
+ for (HashAlgorithm ha : testAlgo) {
+ signatureConfig.setDigestAlgo(ha);
+ OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
+ signatureConfig.setOpcPackage(pkg);
+
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(signatureConfig);
+
+ si.confirmSignature();
+ boolean b = si.verifySignature();
+ pkg.close();
+
+ assertTrue(b);
+ }
+ }
+
+
+ private void sign(OPCPackage pkgCopy, String alias, String signerDn, int signerCount) throws Exception {
+ initKeyPair(alias, signerDn);
+
+ SignatureConfig signatureConfig = new SignatureConfig();
+ signatureConfig.setKey(keyPair.getPrivate());
+ signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
+ signatureConfig.setExecutionTime(cal.getTime());
+ signatureConfig.setDigestAlgo(HashAlgorithm.sha1);
+ signatureConfig.setOpcPackage(pkgCopy);
+
+ SignatureInfo si = new SignatureInfo();
+ si.setSignatureConfig(signatureConfig);
+
+ Document document = DocumentHelper.createDocument();
+
+ // operate
+ DigestInfo digestInfo = si.preSign(document, null);
+
+ // verify
+ assertNotNull(digestInfo);
+ LOG.log(POILogger.DEBUG, "digest algo: " + digestInfo.hashAlgo);
+ LOG.log(POILogger.DEBUG, "digest description: " + digestInfo.description);
+ assertEquals("Office OpenXML Document", digestInfo.description);
+ assertNotNull(digestInfo.hashAlgo);
+ assertNotNull(digestInfo.digestValue);
+
+ // setup: key material, signature value
+ byte[] signatureValue = si.signDigest(digestInfo.digestValue);
+
+ // operate: postSign
+ si.postSign(document, signatureValue);
+
+ // verify: signature
+ si.getSignatureConfig().setOpcPackage(pkgCopy);
+ List result = new ArrayList();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
+ }
+ }
+ assertEquals(signerCount, result.size());
+ }
+
+ private void initKeyPair(String alias, String subjectDN) throws Exception {
+ final char password[] = "test".toCharArray();
+ File file = new File("build/test.pfx");
+
+ KeyStore keystore = KeyStore.getInstance("PKCS12");
+
+ if (file.exists()) {
+ FileInputStream fis = new FileInputStream(file);
+ keystore.load(fis, password);
+ fis.close();
+ } else {
+ keystore.load(null, password);
+ }
+
+ if (keystore.isKeyEntry(alias)) {
+ Key key = keystore.getKey(alias, password);
+ x509 = (X509Certificate)keystore.getCertificate(alias);
+ keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key);
+ } else {
+ keyPair = PkiTestUtils.generateKeyPair();
+ Calendar cal = Calendar.getInstance();
+ Date notBefore = cal.getTime();
+ cal.add(Calendar.YEAR, 1);
+ Date notAfter = cal.getTime();
+ KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
+
+ x509 = PkiTestUtils.generateCertificate(keyPair.getPublic(), subjectDN
+ , notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, keyUsage);
+
+ keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[]{x509});
+ FileOutputStream fos = new FileOutputStream(file);
+ keystore.store(fos, password);
+ fos.close();
+ }
+ }
+
+ private static File copy(File input) throws IOException {
+ String extension = input.getName().replaceAll(".*?(\\.[^.]+)?$", "$1");
+ if (extension == null || "".equals(extension)) extension = ".zip";
+ File tmpFile = new File("build", "sigtest"+extension);
+ FileOutputStream fos = new FileOutputStream(tmpFile);
+ FileInputStream fis = new FileInputStream(input);
+ IOUtils.copy(fis, fos);
+ fis.close();
+ fos.close();
+ return tmpFile;
+ }
+
+}
diff --git a/src/testcases/org/apache/poi/POIDataSamples.java b/src/testcases/org/apache/poi/POIDataSamples.java
index b335215390..a62e664e1e 100644
--- a/src/testcases/org/apache/poi/POIDataSamples.java
+++ b/src/testcases/org/apache/poi/POIDataSamples.java
@@ -44,6 +44,7 @@ public final class POIDataSamples {
private static POIDataSamples _instHPSF;
private static POIDataSamples _instHPBF;
private static POIDataSamples _instHSMF;
+ private static POIDataSamples _instXmlDSign;
private File _resolvedDataDir;
/** true if standard system propery is not set,
@@ -114,6 +115,12 @@ public final class POIDataSamples {
if(_instHSMF == null) _instHSMF = new POIDataSamples("hsmf");
return _instHSMF;
}
+
+ public static POIDataSamples getXmlDSignInstance(){
+ if(_instXmlDSign == null) _instXmlDSign = new POIDataSamples("xmldsign");
+ return _instXmlDSign;
+ }
+
/**
* Opens a sample file from the test data directory
*
diff --git a/test-data/xmldsign/Office2010-SP1-XAdES-X-L.docx b/test-data/xmldsign/Office2010-SP1-XAdES-X-L.docx
new file mode 100644
index 0000000000..4aaa772a0d
Binary files /dev/null and b/test-data/xmldsign/Office2010-SP1-XAdES-X-L.docx differ
diff --git a/test-data/xmldsign/chaintest.pfx b/test-data/xmldsign/chaintest.pfx
new file mode 100644
index 0000000000..e92106d2bb
Binary files /dev/null and b/test-data/xmldsign/chaintest.pfx differ
diff --git a/test-data/xmldsign/hello-world-office-2010-technical-preview-unsigned.docx b/test-data/xmldsign/hello-world-office-2010-technical-preview-unsigned.docx
new file mode 100644
index 0000000000..5162b67c60
Binary files /dev/null and b/test-data/xmldsign/hello-world-office-2010-technical-preview-unsigned.docx differ
diff --git a/test-data/xmldsign/hello-world-office-2010-technical-preview.docx b/test-data/xmldsign/hello-world-office-2010-technical-preview.docx
new file mode 100644
index 0000000000..cbd4277564
Binary files /dev/null and b/test-data/xmldsign/hello-world-office-2010-technical-preview.docx differ
diff --git a/test-data/xmldsign/hello-world-signed-twice.docx b/test-data/xmldsign/hello-world-signed-twice.docx
new file mode 100644
index 0000000000..96c91e957e
Binary files /dev/null and b/test-data/xmldsign/hello-world-signed-twice.docx differ
diff --git a/test-data/xmldsign/hello-world-signed.docx b/test-data/xmldsign/hello-world-signed.docx
new file mode 100644
index 0000000000..79a7bbb81f
Binary files /dev/null and b/test-data/xmldsign/hello-world-signed.docx differ
diff --git a/test-data/xmldsign/hello-world-signed.pptx b/test-data/xmldsign/hello-world-signed.pptx
new file mode 100644
index 0000000000..9b37033f54
Binary files /dev/null and b/test-data/xmldsign/hello-world-signed.pptx differ
diff --git a/test-data/xmldsign/hello-world-signed.xlsx b/test-data/xmldsign/hello-world-signed.xlsx
new file mode 100644
index 0000000000..0d45c53ede
Binary files /dev/null and b/test-data/xmldsign/hello-world-signed.xlsx differ
diff --git a/test-data/xmldsign/hello-world-unsigned.docx b/test-data/xmldsign/hello-world-unsigned.docx
new file mode 100644
index 0000000000..1790c961ce
Binary files /dev/null and b/test-data/xmldsign/hello-world-unsigned.docx differ
diff --git a/test-data/xmldsign/hello-world-unsigned.pptx b/test-data/xmldsign/hello-world-unsigned.pptx
new file mode 100644
index 0000000000..ca42529a9a
Binary files /dev/null and b/test-data/xmldsign/hello-world-unsigned.pptx differ
diff --git a/test-data/xmldsign/hello-world-unsigned.xlsx b/test-data/xmldsign/hello-world-unsigned.xlsx
new file mode 100644
index 0000000000..b99143e92c
Binary files /dev/null and b/test-data/xmldsign/hello-world-unsigned.xlsx differ
diff --git a/test-data/xmldsign/hyperlink-example-signed.docx b/test-data/xmldsign/hyperlink-example-signed.docx
new file mode 100644
index 0000000000..f8698fe4d7
Binary files /dev/null and b/test-data/xmldsign/hyperlink-example-signed.docx differ
diff --git a/test-data/xmldsign/ms-office-2010-signed.docx b/test-data/xmldsign/ms-office-2010-signed.docx
new file mode 100644
index 0000000000..61e4e2a1b8
Binary files /dev/null and b/test-data/xmldsign/ms-office-2010-signed.docx differ
diff --git a/test-data/xmldsign/ms-office-2010-signed.pptx b/test-data/xmldsign/ms-office-2010-signed.pptx
new file mode 100644
index 0000000000..c70f153248
Binary files /dev/null and b/test-data/xmldsign/ms-office-2010-signed.pptx differ
diff --git a/test-data/xmldsign/ms-office-2010-signed.xlsx b/test-data/xmldsign/ms-office-2010-signed.xlsx
new file mode 100644
index 0000000000..d8ba05b1da
Binary files /dev/null and b/test-data/xmldsign/ms-office-2010-signed.xlsx differ
diff --git a/test-data/xmldsign/signed.docx b/test-data/xmldsign/signed.docx
new file mode 100644
index 0000000000..98f3b8d841
Binary files /dev/null and b/test-data/xmldsign/signed.docx differ