]> source.dussan.org Git - poi.git/commitdiff
another round of refactoring, limited exception declarations, more javadocs
authorAndreas Beeker <kiwiwings@apache.org>
Fri, 3 Oct 2014 22:24:09 +0000 (22:24 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Fri, 3 Oct 2014 22:24:09 +0000 (22:24 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1629332 13f79535-47bb-0310-9956-ffa450edef68

src/ooxml/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/EnvelopedSignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/KeyInfoSignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/Office2010SignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/SignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESSignatureFacet.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java

index 50dd68ddef134912b84b01b02e4f93573b1bece5..dad12d2e8f0e9eed09e0ef5a96352796e7de1bc1 100644 (file)
@@ -34,7 +34,6 @@ import javax.xml.crypto.URIDereferencer;
 import javax.xml.crypto.URIReference;\r
 import javax.xml.crypto.URIReferenceException;\r
 import javax.xml.crypto.XMLCryptoContext;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
 \r
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
 import org.apache.poi.openxml4j.opc.PackagePart;\r
@@ -54,16 +53,15 @@ public class OOXMLURIDereferencer implements URIDereferencer, SignatureConfigura
     private SignatureConfig signatureConfig;\r
     private URIDereferencer baseUriDereferencer;\r
 \r
-    public OOXMLURIDereferencer() {\r
-        XMLSignatureFactory xmlSignatureFactory = SignatureInfo.getSignatureFactory();\r
-        this.baseUriDereferencer = xmlSignatureFactory.getURIDereferencer();\r
-    }\r
-    \r
     public void setSignatureConfig(SignatureConfig signatureConfig) {\r
         this.signatureConfig = signatureConfig;\r
     }\r
 \r
     public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException {\r
+        if (baseUriDereferencer == null) {\r
+            baseUriDereferencer = signatureConfig.getSignatureFactory().getURIDereferencer();\r
+        }\r
+        \r
         if (null == uriReference) {\r
             throw new NullPointerException("URIReference cannot be null");\r
         }\r
index 0ea45faeed425e7ff5d2607d8ae3efde110fa36b..52ba1f3ba1645c1c82fab8b6ab9b91b1f6874069 100644 (file)
@@ -21,6 +21,7 @@ import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS
 import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XADES_132_NS;\r
 \r
 import java.security.PrivateKey;\r
+import java.security.Provider;\r
 import java.security.cert.X509Certificate;\r
 import java.util.ArrayList;\r
 import java.util.Date;\r
@@ -32,6 +33,8 @@ import java.util.UUID;
 import javax.xml.crypto.URIDereferencer;\r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
 import javax.xml.crypto.dsig.DigestMethod;\r
+import javax.xml.crypto.dsig.XMLSignatureFactory;\r
+import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;\r
 \r
 import org.apache.poi.EncryptedDocumentException;\r
 import org.apache.poi.openxml4j.opc.OPCPackage;\r
@@ -46,21 +49,28 @@ import org.apache.poi.poifs.crypt.dsig.services.SignaturePolicyService;
 import org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService;\r
 import org.apache.poi.poifs.crypt.dsig.services.TimeStampService;\r
 import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator;\r
+import org.apache.poi.util.POILogFactory;\r
+import org.apache.poi.util.POILogger;\r
 import org.w3c.dom.events.EventListener;\r
 \r
 /**\r
  * This class bundles the configuration options used for the existing\r
  * signature facets.\r
- * Apart of the opc-package (thread local) most values will probably be constant, so\r
+ * Apart of the thread local members (e.g. opc-package) most values will probably be constant, so\r
  * it might be configured centrally (e.g. by spring) \r
  */\r
 public class SignatureConfig {\r
+\r
+    private static final POILogger LOG = POILogFactory.getLogger(SignatureConfig.class);\r
     \r
     public static interface SignatureConfigurable {\r
         void setSignatureConfig(SignatureConfig signatureConfig);        \r
     }\r
 \r
     private ThreadLocal<OPCPackage> opcPackage = new ThreadLocal<OPCPackage>();\r
+    private ThreadLocal<XMLSignatureFactory> signatureFactory = new ThreadLocal<XMLSignatureFactory>();\r
+    private ThreadLocal<KeyInfoFactory> keyInfoFactory = new ThreadLocal<KeyInfoFactory>();\r
+    private ThreadLocal<Provider> provider = new ThreadLocal<Provider>();\r
     \r
     private List<SignatureFacet> signatureFacets = new ArrayList<SignatureFacet>();\r
     private HashAlgorithm digestAlgo = HashAlgorithm.sha1;\r
@@ -72,7 +82,7 @@ public class SignatureConfig {
      * the optional signature policy service used for XAdES-EPES.\r
      */\r
     private SignaturePolicyService signaturePolicyService;\r
-    private URIDereferencer uriDereferencer = new OOXMLURIDereferencer();\r
+    private URIDereferencer uriDereferencer = null;\r
     private String canonicalizationMethod = CanonicalizationMethod.INCLUSIVE;\r
     \r
     private boolean includeEntireCertificateChain = true;\r
@@ -146,13 +156,22 @@ public class SignatureConfig {
      */\r
     Map<String,String> namespacePrefixes = new HashMap<String,String>();\r
     \r
+    /**\r
+     * Inits and checks the config object.\r
+     * If not set previously, complex configuration properties also get \r
+     * created/initialized via this initialization call.\r
+     *\r
+     * @param onlyValidation if true, only a subset of the properties\r
+     * is initialized, which are necessary for validation. If false,\r
+     * also the other properties needed for signing are been taken care of\r
+     */\r
     protected void init(boolean onlyValidation) {\r
-        if (uriDereferencer == null) {\r
-            throw new EncryptedDocumentException("uriDereferencer is null");\r
-        }\r
         if (opcPackage == null) {\r
             throw new EncryptedDocumentException("opcPackage is null");\r
         }\r
+        if (uriDereferencer == null) {\r
+            uriDereferencer = new OOXMLURIDereferencer();\r
+        }\r
         if (uriDereferencer instanceof SignatureConfigurable) {\r
             ((SignatureConfigurable)uriDereferencer).setSignatureConfig(this);\r
         }\r
@@ -195,68 +214,155 @@ public class SignatureConfig {
         }\r
     }\r
     \r
-    public void addSignatureFacet(SignatureFacet sf) {\r
-        signatureFacets.add(sf);\r
+    /**\r
+     * @param signatureFacet the signature facet is appended to facet list \r
+     */\r
+    public void addSignatureFacet(SignatureFacet signatureFacet) {\r
+        signatureFacets.add(signatureFacet);\r
     }\r
     \r
+    /**\r
+     * @return the list of facets, may be empty when the config object is not initialized\r
+     */\r
     public List<SignatureFacet> getSignatureFacets() {\r
         return signatureFacets;\r
     }\r
+\r
+    /**\r
+     * @param signatureFacets the new list of facets\r
+     */\r
     public void setSignatureFacets(List<SignatureFacet> signatureFacets) {\r
         this.signatureFacets = signatureFacets;\r
     }\r
+\r
+    /**\r
+     * @return the main digest algorithm, defaults to sha-1\r
+     */\r
     public HashAlgorithm getDigestAlgo() {\r
         return digestAlgo;\r
     }\r
+\r
+    /**\r
+     * @param digestAlgo the main digest algorithm\r
+     */\r
     public void setDigestAlgo(HashAlgorithm digestAlgo) {\r
         this.digestAlgo = digestAlgo;\r
     }\r
+    \r
+    /**\r
+     * @return the opc package to be used by this thread, stored as thread-local\r
+     */\r
     public OPCPackage getOpcPackage() {\r
         return opcPackage.get();\r
     }\r
+    \r
+    /**\r
+     * @param opcPackage the opc package to be handled by this thread, stored as thread-local\r
+     */\r
     public void setOpcPackage(OPCPackage opcPackage) {\r
         this.opcPackage.set(opcPackage);\r
     }\r
+\r
+    /**\r
+     * @return the private key\r
+     */\r
     public PrivateKey getKey() {\r
         return key;\r
     }\r
+\r
+    /**\r
+     * @param key the private key\r
+     */\r
     public void setKey(PrivateKey key) {\r
         this.key = key;\r
     }\r
+\r
+    /**\r
+     * @return the certificate chain, index 0 is usually the certificate matching\r
+     * the private key\r
+     */\r
     public List<X509Certificate> getSigningCertificateChain() {\r
         return signingCertificateChain;\r
     }\r
+\r
+    /**\r
+     * @param signingCertificateChain the certificate chain, index 0 should be\r
+     * the certificate matching the private key\r
+     */\r
     public void setSigningCertificateChain(\r
             List<X509Certificate> signingCertificateChain) {\r
         this.signingCertificateChain = signingCertificateChain;\r
     }\r
+\r
+    /**\r
+     * @return the time at which the document is signed, also used for the timestamp service.\r
+     * defaults to now\r
+     */\r
     public Date getExecutionTime() {\r
         return executionTime;\r
     }\r
+\r
+    /**\r
+     * @param executionTime sets the time at which the document ought to be signed\r
+     */\r
     public void setExecutionTime(Date executionTime) {\r
         this.executionTime = executionTime;\r
     }\r
+    \r
+    /**\r
+     * @return the service to be used for XAdES-EPES properties. There's no default implementation\r
+     */\r
     public SignaturePolicyService getSignaturePolicyService() {\r
         return signaturePolicyService;\r
     }\r
+\r
+    /**\r
+     * @param signaturePolicyService the service to be used for XAdES-EPES properties\r
+     */\r
     public void setSignaturePolicyService(SignaturePolicyService signaturePolicyService) {\r
         this.signaturePolicyService = signaturePolicyService;\r
     }\r
+\r
+    /**\r
+     * @return the dereferencer used for Reference/@URI attributes, defaults to {@link OOXMLURIDereferencer}\r
+     */\r
     public URIDereferencer getUriDereferencer() {\r
         return uriDereferencer;\r
     }\r
+\r
+    /**\r
+     * @param uriDereferencer the dereferencer used for Reference/@URI attributes\r
+     */\r
     public void setUriDereferencer(URIDereferencer uriDereferencer) {\r
         this.uriDereferencer = uriDereferencer;\r
     }\r
+\r
+    /**\r
+     * @return Gives back the human-readable description of what the citizen\r
+     * will be signing. The default value is "Office OpenXML Document".\r
+     */\r
     public String getSignatureDescription() {\r
         return signatureDescription;\r
     }\r
+\r
+    /**\r
+     * @param signatureDescription the human-readable description of\r
+     * what the citizen will be signing.\r
+     */\r
     public void setSignatureDescription(String signatureDescription) {\r
         this.signatureDescription = signatureDescription;\r
     }\r
+    \r
+    /**\r
+     * @return the default canonicalization method, defaults to INCLUSIVE\r
+     */\r
     public String getCanonicalizationMethod() {\r
         return canonicalizationMethod;\r
     }\r
+    \r
+    /**\r
+     * @param canonicalizationMethod the default canonicalization method\r
+     */\r
     public void setCanonicalizationMethod(String canonicalizationMethod) {\r
         this.canonicalizationMethod = canonicalizationMethod;\r
     }\r
@@ -469,4 +575,59 @@ public class SignatureConfig {
         }\r
     }\r
     \r
+    public void setSignatureFactory(XMLSignatureFactory signatureFactory) {\r
+        this.signatureFactory.set(signatureFactory);\r
+    }\r
+    \r
+    public XMLSignatureFactory getSignatureFactory() {\r
+        XMLSignatureFactory sigFac = signatureFactory.get();\r
+        if (sigFac == null) {\r
+            sigFac = XMLSignatureFactory.getInstance("DOM", getProvider());\r
+            setSignatureFactory(sigFac);\r
+        }\r
+        return sigFac;\r
+    }\r
+\r
+    public void setKeyInfoFactory(KeyInfoFactory keyInfoFactory) {\r
+        this.keyInfoFactory.set(keyInfoFactory);\r
+    }\r
+    \r
+    public KeyInfoFactory getKeyInfoFactory() {\r
+        KeyInfoFactory keyFac = keyInfoFactory.get();\r
+        if (keyFac == null) {\r
+            keyFac = KeyInfoFactory.getInstance("DOM", getProvider());\r
+            setKeyInfoFactory(keyFac);\r
+        }\r
+        return keyFac;\r
+    }\r
+\r
+    // currently classes are linked to Apache Santuario, so this might be superfluous \r
+    public Provider getProvider() {\r
+        Provider prov = provider.get();\r
+        if (prov == null) {\r
+            String dsigProviderNames[] = {\r
+                System.getProperty("jsr105Provider"),\r
+                "org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI", // Santuario xmlsec\r
+                "org.jcp.xml.dsig.internal.dom.XMLDSigRI"         // JDK xmlsec\r
+            };\r
+            for (String pn : dsigProviderNames) {\r
+                if (pn == null) continue;\r
+                try {\r
+                    prov = (Provider)Class.forName(pn).newInstance();\r
+                    break;\r
+                } catch (Exception e) {\r
+                    LOG.log(POILogger.DEBUG, "XMLDsig-Provider '"+pn+"' can't be found - trying next.");\r
+                }\r
+            }\r
+        }\r
+\r
+        if (prov == null) {\r
+            throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!");\r
+        }\r
+        \r
+        return prov;\r
+    }\r
+    \r
+\r
+\r
 }\r
index 3aa9be6e0090b4ab01db418382ac9e023f545d02..94de8950a8e08f7fbfa982d59f10f085173eeb08 100644 (file)
@@ -30,12 +30,8 @@ import java.io.ByteArrayOutputStream;
 import java.io.File;\r
 import java.io.IOException;\r
 import java.io.OutputStream;\r
-import java.net.URISyntaxException;\r
-import java.security.InvalidAlgorithmParameterException;\r
+import java.security.GeneralSecurityException;\r
 import java.security.MessageDigest;\r
-import java.security.NoSuchAlgorithmException;\r
-import java.security.NoSuchProviderException;\r
-import java.security.Provider;\r
 import java.security.cert.X509Certificate;\r
 import java.util.ArrayList;\r
 import java.util.Collections;\r
@@ -50,7 +46,6 @@ import javax.xml.crypto.MarshalException;
 import javax.xml.crypto.URIDereferencer;\r
 import javax.xml.crypto.XMLStructure;\r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
-import javax.xml.crypto.dsig.DigestMethod;\r
 import javax.xml.crypto.dsig.Manifest;\r
 import javax.xml.crypto.dsig.Reference;\r
 import javax.xml.crypto.dsig.SignatureMethod;\r
@@ -62,11 +57,7 @@ import javax.xml.crypto.dsig.XMLSignatureException;
 import javax.xml.crypto.dsig.XMLSignatureFactory;\r
 import javax.xml.crypto.dsig.dom.DOMSignContext;\r
 import javax.xml.crypto.dsig.dom.DOMValidateContext;\r
-import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;\r
 import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;\r
-import javax.xml.parsers.ParserConfigurationException;\r
-import javax.xml.transform.TransformerException;\r
-import javax.xml.transform.TransformerFactoryConfigurationError;\r
 import javax.xml.xpath.XPath;\r
 import javax.xml.xpath.XPathConstants;\r
 import javax.xml.xpath.XPathFactory;\r
@@ -103,7 +94,6 @@ import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;\r
 import org.w3c.dom.events.EventListener;\r
 import org.w3c.dom.events.EventTarget;\r
-import org.xml.sax.SAXException;\r
 \r
 \r
 /**\r
@@ -144,7 +134,7 @@ import org.xml.sax.SAXException;
  * SignatureConfig signatureConfig = new SignatureConfig();\r
  * signatureConfig.setKey(keyPair.getPrivate());\r
  * signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));\r
- * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ);\r
+ * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE);\r
  * signatureConfig.setOpcPackage(pkg);\r
  * \r
  * // adding the signature document to the package\r
@@ -220,7 +210,7 @@ public class SignatureInfo implements SignatureConfigurable {
                 domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);\r
                 domValidateContext.setURIDereferencer(signatureConfig.getUriDereferencer());\r
     \r
-                XMLSignatureFactory xmlSignatureFactory = getSignatureFactory();\r
+                XMLSignatureFactory xmlSignatureFactory = signatureConfig.getSignatureFactory();\r
                 XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);\r
                 boolean valid = xmlSignature.validate(domValidateContext);\r
 \r
@@ -258,8 +248,7 @@ public class SignatureInfo implements SignatureConfigurable {
         return false;\r
     }\r
 \r
-    public void confirmSignature()\r
-    throws NoSuchAlgorithmException, IOException, MarshalException, ParserConfigurationException, XmlException, InvalidAlgorithmParameterException, NoSuchProviderException, XMLSignatureException, TransformerFactoryConfigurationError, TransformerException, SAXException, URISyntaxException {\r
+    public void confirmSignature() throws XMLSignatureException, MarshalException {\r
         Document document = DocumentHelper.createDocument();\r
         \r
         // operate\r
@@ -335,33 +324,6 @@ public class SignatureInfo implements SignatureConfigurable {
         };\r
     }\r
     \r
-    public static XMLSignatureFactory getSignatureFactory() {\r
-        return XMLSignatureFactory.getInstance("DOM", getProvider());\r
-    }\r
-\r
-    public static KeyInfoFactory getKeyInfoFactory() {\r
-        return KeyInfoFactory.getInstance("DOM", getProvider());\r
-    }\r
-\r
-    // currently classes are linked to Apache Santuario, so this might be superfluous \r
-    public static Provider getProvider() {\r
-        String dsigProviderNames[] = {\r
-            System.getProperty("jsr105Provider"),\r
-            "org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI", // Santuario xmlsec\r
-            "org.jcp.xml.dsig.internal.dom.XMLDSigRI"         // JDK xmlsec\r
-        };\r
-        for (String pn : dsigProviderNames) {\r
-            if (pn == null) continue;\r
-            try {\r
-                return (Provider)Class.forName(pn).newInstance();\r
-            } catch (Exception e) {\r
-                LOG.log(POILogger.DEBUG, "XMLDsig-Provider '"+pn+"' can't be found - trying next.");\r
-            }\r
-        }\r
-\r
-        throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!");\r
-    }\r
-    \r
     protected static synchronized void initXmlProvider() {\r
         if (isInitialized) return;\r
         isInitialized = true;\r
@@ -381,11 +343,7 @@ public class SignatureInfo implements SignatureConfigurable {
      */\r
     @SuppressWarnings("unchecked")\r
     public DigestInfo preSign(Document document, List<DigestInfo> digestInfos)\r
-        throws ParserConfigurationException, NoSuchAlgorithmException,\r
-        InvalidAlgorithmParameterException, MarshalException,\r
-        javax.xml.crypto.dsig.XMLSignatureException,\r
-        TransformerFactoryConfigurationError, TransformerException,\r
-        IOException, SAXException, NoSuchProviderException, XmlException, URISyntaxException {\r
+    throws XMLSignatureException, MarshalException {\r
         signatureConfig.init(false);\r
         \r
         // it's necessary to explicitly set the mdssi namespace, but the sign() method has no\r
@@ -413,7 +371,7 @@ public class SignatureInfo implements SignatureConfigurable {
         }\r
         xmlSignContext.setDefaultNamespacePrefix(""); // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));\r
         \r
-        XMLSignatureFactory signatureFactory = SignatureInfo.getSignatureFactory();\r
+        XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();\r
 \r
         /*\r
          * Add ds:References that come from signing client local files.\r
@@ -422,13 +380,9 @@ public class SignatureInfo implements SignatureConfigurable {
         for (DigestInfo digestInfo : safe(digestInfos)) {\r
             byte[] documentDigestValue = digestInfo.digestValue;\r
 \r
-            DigestMethod digestMethod = signatureFactory.newDigestMethod\r
-                (signatureConfig.getDigestMethodUri(), null);\r
-\r
             String uri = new File(digestInfo.description).getName();\r
-\r
-            Reference reference = signatureFactory.newReference\r
-                (uri, digestMethod, null, null, null, documentDigestValue);\r
+            Reference reference = SignatureFacet.newReference\r
+                (uri, null, null, null, documentDigestValue, signatureConfig);\r
             references.add(reference);\r
         }\r
 \r
@@ -438,19 +392,24 @@ public class SignatureInfo implements SignatureConfigurable {
         List<XMLObject> objects = new ArrayList<XMLObject>();\r
         for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {\r
             LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());\r
-            signatureFacet.preSign(document, signatureFactory, references, objects);\r
+            signatureFacet.preSign(document, references, objects);\r
         }\r
 \r
         /*\r
          * ds:SignedInfo\r
          */\r
-        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod\r
-            (signatureConfig.getSignatureMethod(), null);\r
-        CanonicalizationMethod canonicalizationMethod = signatureFactory\r
-            .newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(),\r
-            (C14NMethodParameterSpec) null);\r
-        SignedInfo signedInfo = signatureFactory.newSignedInfo(\r
-            canonicalizationMethod, signatureMethod, references);\r
+        SignedInfo signedInfo;\r
+        try {\r
+            SignatureMethod signatureMethod = signatureFactory.newSignatureMethod\r
+                (signatureConfig.getSignatureMethod(), null);\r
+            CanonicalizationMethod canonicalizationMethod = signatureFactory\r
+                .newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(),\r
+                (C14NMethodParameterSpec) null);\r
+            signedInfo = signatureFactory.newSignedInfo(\r
+                canonicalizationMethod, signatureMethod, references);\r
+        } catch (GeneralSecurityException e) {\r
+            throw new XMLSignatureException(e);\r
+        }\r
 \r
         /*\r
          * JSR105 ds:Signature creation\r
@@ -524,7 +483,7 @@ public class SignatureInfo implements SignatureConfigurable {
      * Normally {@link #confirmSignature()} is sufficient to be used.\r
      */\r
     public void postSign(Document document, byte[] signatureValue)\r
-    throws IOException, MarshalException, ParserConfigurationException, XmlException {\r
+    throws MarshalException {\r
         LOG.log(POILogger.DEBUG, "postSign");\r
 \r
         /*\r
@@ -554,7 +513,7 @@ public class SignatureInfo implements SignatureConfigurable {
         writeDocument(document);\r
     }\r
 \r
-    protected void writeDocument(Document document) throws IOException, XmlException {\r
+    protected void writeDocument(Document document) throws MarshalException {\r
         XmlOptions xo = new XmlOptions();\r
         Map<String,String> namespaceMap = new HashMap<String,String>();\r
         for(Map.Entry<String,String> entry : signatureConfig.getNamespacePrefixes().entrySet()){\r
@@ -578,7 +537,7 @@ public class SignatureInfo implements SignatureConfigurable {
             // <Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/>\r
             sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs");\r
         } catch (InvalidFormatException e) {\r
-            throw new IOException(e);\r
+            throw new MarshalException(e);\r
         }\r
         \r
         PackagePart sigPart = pkg.getPart(sigPartName);\r
@@ -586,10 +545,14 @@ public class SignatureInfo implements SignatureConfigurable {
             sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);\r
         }\r
         \r
-        OutputStream os = sigPart.getOutputStream();\r
-        SignatureDocument sigDoc = SignatureDocument.Factory.parse(document);\r
-        sigDoc.save(os, xo);\r
-        os.close();\r
+        try {\r
+            OutputStream os = sigPart.getOutputStream();\r
+            SignatureDocument sigDoc = SignatureDocument.Factory.parse(document);\r
+            sigDoc.save(os, xo);\r
+            os.close();\r
+        } catch (Exception e) {\r
+            throw new MarshalException("Unable to write signature document", e);\r
+        }\r
         \r
         PackagePart sigsPart = pkg.getPart(sigsPartName);\r
         if (sigsPart == null) {\r
index 9e2cbab980dce6380aa3e751d9b36e06bf1309c8..28b09ebab2eb30ffc2d004d01c917ba8bfd22738 100644 (file)
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.security.InvalidAlgorithmParameterException;\r
-import java.security.NoSuchAlgorithmException;\r
 import java.util.ArrayList;\r
 import java.util.List;\r
 \r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
-import javax.xml.crypto.dsig.DigestMethod;\r
 import javax.xml.crypto.dsig.Reference;\r
 import javax.xml.crypto.dsig.Transform;\r
 import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
-import javax.xml.crypto.dsig.spec.TransformParameterSpec;\r
+import javax.xml.crypto.dsig.XMLSignatureException;\r
 \r
-import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
 import org.w3c.dom.Document;\r
 \r
 /**\r
@@ -46,39 +41,20 @@ import org.w3c.dom.Document;
  * @author Frank Cornelis\r
  * \r
  */\r
-public class EnvelopedSignatureFacet implements SignatureFacet {\r
-\r
-    private SignatureConfig signatureConfig;\r
-\r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-        this.signatureConfig = signatureConfig;\r
-    }\r
-    \r
-    @Override\r
-    public void postSign(Document document) {\r
-        // empty\r
-    }\r
+public class EnvelopedSignatureFacet extends SignatureFacet {\r
 \r
     @Override\r
     public void preSign(Document document\r
-        , XMLSignatureFactory signatureFactory\r
         , List<Reference> references\r
         , List<XMLObject> objects)\r
-    throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
-        DigestMethod digestMethod = signatureFactory.newDigestMethod\r
-            (signatureConfig.getDigestMethodUri(), null);\r
-\r
+    throws XMLSignatureException {\r
         List<Transform> transforms = new ArrayList<Transform>();\r
-        Transform envelopedTransform = signatureFactory.newTransform\r
-            (CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null);\r
+        Transform envelopedTransform = newTransform(CanonicalizationMethod.ENVELOPED);\r
         transforms.add(envelopedTransform);\r
-        Transform exclusiveTransform = signatureFactory.newTransform\r
-            (CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);\r
+        Transform exclusiveTransform = newTransform(CanonicalizationMethod.EXCLUSIVE);\r
         transforms.add(exclusiveTransform);\r
 \r
-        Reference reference = signatureFactory.newReference("", digestMethod,\r
-                transforms, null, null);\r
-\r
+        Reference reference = newReference("", transforms, null, null, null);\r
         references.add(reference);\r
     }\r
 }\r
index 8fee7f56a7d669024881604e009d76f0c9e15bd0..fca30abd921ecbebf91febb9a4f72890bb4347cc 100644 (file)
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.security.InvalidAlgorithmParameterException;\r
 import java.security.Key;\r
 import java.security.KeyException;\r
-import java.security.NoSuchAlgorithmException;\r
 import java.security.cert.X509Certificate;\r
 import java.util.ArrayList;\r
 import java.util.List;\r
@@ -35,9 +33,6 @@ import java.util.Map;
 \r
 import javax.xml.crypto.MarshalException;\r
 import javax.xml.crypto.dom.DOMStructure;\r
-import javax.xml.crypto.dsig.Reference;\r
-import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
 import javax.xml.crypto.dsig.dom.DOMSignContext;\r
 import javax.xml.crypto.dsig.keyinfo.KeyInfo;\r
 import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;\r
@@ -45,8 +40,6 @@ import javax.xml.crypto.dsig.keyinfo.KeyValue;
 import javax.xml.crypto.dsig.keyinfo.X509Data;\r
 \r
 import org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo;\r
-import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
-import org.apache.poi.poifs.crypt.dsig.SignatureInfo;\r
 import org.apache.poi.util.POILogFactory;\r
 import org.apache.poi.util.POILogger;\r
 import org.w3c.dom.Document;\r
@@ -60,16 +53,10 @@ import org.w3c.dom.NodeList;
  * @author Frank Cornelis\r
  * \r
  */\r
-public class KeyInfoSignatureFacet implements SignatureFacet {\r
+public class KeyInfoSignatureFacet extends SignatureFacet {\r
 \r
     private static final POILogger LOG = POILogFactory.getLogger(KeyInfoSignatureFacet.class);\r
     \r
-    SignatureConfig signatureConfig;\r
-\r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-         this.signatureConfig = signatureConfig;\r
-    }\r
-\r
     @Override\r
     public void postSign(Document document) \r
     throws MarshalException {\r
@@ -86,7 +73,7 @@ public class KeyInfoSignatureFacet implements SignatureFacet {
         /*\r
          * Construct the ds:KeyInfo element using JSR 105.\r
          */\r
-        KeyInfoFactory keyInfoFactory = SignatureInfo.getKeyInfoFactory();\r
+        KeyInfoFactory keyInfoFactory = signatureConfig.getKeyInfoFactory();\r
         List<Object> x509DataObjects = new ArrayList<Object>();\r
         X509Certificate signingCertificate = signatureConfig.getSigningCertificateChain().get(0);\r
 \r
@@ -104,8 +91,8 @@ public class KeyInfoSignatureFacet implements SignatureFacet {
 \r
         if (signatureConfig.isIncludeIssuerSerial()) {\r
             x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(\r
-                    signingCertificate.getIssuerX500Principal().toString(),\r
-                    signingCertificate.getSerialNumber()));\r
+                signingCertificate.getIssuerX500Principal().toString(),\r
+                signingCertificate.getSerialNumber()));\r
         }\r
 \r
         if (signatureConfig.isIncludeEntireCertificateChain()) {\r
@@ -155,14 +142,4 @@ public class KeyInfoSignatureFacet implements SignatureFacet {
             nextSibling.getParentNode().insertBefore(kiNl.item(0), nextSibling);\r
         }\r
     }\r
-\r
-    @Override\r
-    public void preSign(\r
-          Document document\r
-        , XMLSignatureFactory signatureFactory\r
-        , List<Reference> references\r
-        , List<XMLObject> objects\r
-    ) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
-        // empty\r
-    }\r
 }
\ No newline at end of file
index 947b498b0ec383c2a22d5c3c856285419530b9b6..59ae52a20c6ee67e9b400072183101c0161e02c4 100644 (file)
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.io.IOException;\r
 import java.net.URI;\r
 import java.net.URISyntaxException;\r
-import java.security.InvalidAlgorithmParameterException;\r
-import java.security.NoSuchAlgorithmException;\r
 import java.text.DateFormat;\r
 import java.text.SimpleDateFormat;\r
 import java.util.ArrayList;\r
@@ -41,15 +38,13 @@ import javax.xml.XMLConstants;
 import javax.xml.crypto.XMLStructure;\r
 import javax.xml.crypto.dom.DOMStructure;\r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
-import javax.xml.crypto.dsig.DigestMethod;\r
 import javax.xml.crypto.dsig.Manifest;\r
 import javax.xml.crypto.dsig.Reference;\r
 import javax.xml.crypto.dsig.SignatureProperties;\r
 import javax.xml.crypto.dsig.SignatureProperty;\r
 import javax.xml.crypto.dsig.Transform;\r
 import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
-import javax.xml.crypto.dsig.spec.TransformParameterSpec;\r
+import javax.xml.crypto.dsig.XMLSignatureException;\r
 \r
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;\r
 import org.apache.poi.openxml4j.opc.ContentTypes;\r
@@ -60,12 +55,10 @@ import org.apache.poi.openxml4j.opc.PackageRelationship;
 import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;\r
 import org.apache.poi.openxml4j.opc.PackagingURIHelper;\r
 import org.apache.poi.openxml4j.opc.TargetMode;\r
-import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
 import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService;\r
 import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService.RelationshipTransformParameterSpec;\r
 import org.apache.poi.util.POILogFactory;\r
 import org.apache.poi.util.POILogger;\r
-import org.apache.xmlbeans.XmlException;\r
 import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.CTSignatureTime;\r
 import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.SignatureTimeDocument;\r
 import org.w3c.dom.Document;\r
@@ -80,64 +73,50 @@ import com.microsoft.schemas.office.x2006.digsig.SignatureInfoV1Document;
  * @author fcorneli\r
  * @see <a href="http://msdn.microsoft.com/en-us/library/cc313071.aspx">[MS-OFFCRYPTO]: Office Document Cryptography Structure</a>\r
  */\r
-public class OOXMLSignatureFacet implements SignatureFacet {\r
+public class OOXMLSignatureFacet extends SignatureFacet {\r
 \r
     private static final POILogger LOG = POILogFactory.getLogger(OOXMLSignatureFacet.class);\r
 \r
-    private SignatureConfig signatureConfig;\r
-\r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-        this.signatureConfig = signatureConfig;\r
-    }\r
-    \r
     @Override\r
     public void preSign(\r
         Document document\r
-        , XMLSignatureFactory signatureFactory\r
         , List<Reference> references\r
         , List<XMLObject> objects)\r
-    throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, URISyntaxException, XmlException {\r
+    throws XMLSignatureException {\r
         LOG.log(POILogger.DEBUG, "pre sign");\r
-        addManifestObject(document, signatureFactory, references, objects);\r
-        addSignatureInfo(document, signatureFactory, references, objects);\r
+        addManifestObject(document, references, objects);\r
+        addSignatureInfo(document, references, objects);\r
     }\r
 \r
     protected void addManifestObject(\r
         Document document\r
-        , XMLSignatureFactory signatureFactory\r
         , List<Reference> references\r
         , List<XMLObject> objects)\r
-    throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, URISyntaxException, XmlException {\r
+    throws XMLSignatureException {\r
 \r
         List<Reference> manifestReferences = new ArrayList<Reference>();\r
-        addManifestReferences(signatureFactory, manifestReferences);\r
-        Manifest manifest =  signatureFactory.newManifest(manifestReferences);\r
+        addManifestReferences(manifestReferences);\r
+        Manifest manifest =  getSignatureFactory().newManifest(manifestReferences);\r
         \r
         String objectId = "idPackageObject"; // really has to be this value.\r
         List<XMLStructure> objectContent = new ArrayList<XMLStructure>();\r
         objectContent.add(manifest);\r
 \r
-        addSignatureTime(document, signatureFactory, objectContent);\r
+        addSignatureTime(document, objectContent);\r
 \r
-        XMLObject xo = signatureFactory.newXMLObject(objectContent, objectId, null, null);\r
+        XMLObject xo = getSignatureFactory().newXMLObject(objectContent, objectId, null, null);\r
         objects.add(xo);\r
 \r
-        DigestMethod digestMethod = signatureFactory.newDigestMethod\r
-            (signatureConfig.getDigestMethodUri(), null);\r
-        Reference reference = signatureFactory.newReference\r
-            ("#" + objectId, digestMethod, null, XML_DIGSIG_NS+"Object", null);\r
+        Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS+"Object", null, null);\r
         references.add(reference);\r
     }\r
 \r
-    protected void addManifestReferences\r
-        (XMLSignatureFactory signatureFactory, List<Reference> manifestReferences)\r
-    throws IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, URISyntaxException, XmlException {\r
+    protected void addManifestReferences(List<Reference> manifestReferences)\r
+    throws XMLSignatureException {\r
 \r
         OPCPackage ooxml = signatureConfig.getOpcPackage();\r
         List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);\r
 \r
-        DigestMethod digestMethod = signatureFactory.newDigestMethod\r
-            (signatureConfig.getDigestMethodUri(), null);\r
         Set<String> digestedPartNames = new HashSet<String>();\r
         for (PackagePart pp : relsEntryNames) {\r
             String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");\r
@@ -147,7 +126,7 @@ public class OOXMLSignatureFacet implements SignatureFacet {
                 prc = new PackageRelationshipCollection(ooxml);\r
                 prc.parseRelationshipsPart(pp);\r
             } catch (InvalidFormatException e) {\r
-                throw new IOException("Invalid relationship descriptor: "+pp.getPartName().getName(), e);\r
+                throw new XMLSignatureException("Invalid relationship descriptor: "+pp.getPartName().getName(), e);\r
             }\r
             \r
             RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();\r
@@ -169,8 +148,12 @@ public class OOXMLSignatureFacet implements SignatureFacet {
 \r
                 // TODO: find a better way ...\r
                 String partName = baseUri + relationship.getTargetURI().toString();\r
-                partName = new URI(partName).normalize().getPath().replace('\\', '/');\r
-                LOG.log(POILogger.DEBUG, "part name: " + partName);\r
+                try {\r
+                    partName = new URI(partName).normalize().getPath().replace('\\', '/');\r
+                    LOG.log(POILogger.DEBUG, "part name: " + partName);\r
+                } catch (URISyntaxException e) {\r
+                    throw new XMLSignatureException(e);\r
+                }\r
                 \r
                 String contentType;\r
                 try {\r
@@ -178,7 +161,7 @@ public class OOXMLSignatureFacet implements SignatureFacet {
                     PackagePart pp2 = ooxml.getPart(relName);\r
                     contentType = pp2.getContentType();\r
                 } catch (InvalidFormatException e) {\r
-                    throw new IOException(e);\r
+                    throw new XMLSignatureException(e);\r
                 }\r
                 \r
                 if (relationshipType.endsWith("customXml")\r
@@ -190,7 +173,7 @@ public class OOXMLSignatureFacet implements SignatureFacet {
                 if (!digestedPartNames.contains(partName)) {\r
                     // We only digest a part once.\r
                     String uri = partName + "?ContentType=" + contentType;\r
-                    Reference reference = signatureFactory.newReference(uri, digestMethod);\r
+                    Reference reference = newReference(uri, null, null, null, null);\r
                     manifestReferences.add(reference);\r
                     digestedPartNames.add(partName);\r
                 }\r
@@ -198,25 +181,18 @@ public class OOXMLSignatureFacet implements SignatureFacet {
             \r
             if (parameterSpec.hasSourceIds()) {\r
                 List<Transform> transforms = new ArrayList<Transform>();\r
-                transforms.add(signatureFactory.newTransform(\r
-                    RelationshipTransformService.TRANSFORM_URI,\r
-                    parameterSpec));\r
-                transforms.add(signatureFactory.newTransform(\r
-                    CanonicalizationMethod.INCLUSIVE,\r
-                    (TransformParameterSpec) null));\r
+                transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));\r
+                transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE));\r
                 String uri = pp.getPartName().getName()\r
                     + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";\r
-                Reference reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null);\r
+                Reference reference = newReference(uri, transforms, null, null, null);\r
                 manifestReferences.add(reference);\r
             }\r
         }\r
     }\r
 \r
 \r
-    protected void addSignatureTime(\r
-        Document document\r
-        , XMLSignatureFactory signatureFactory\r
-        , List<XMLStructure> objectContent) {\r
+    protected void addSignatureTime(Document document, List<XMLStructure> objectContent) {\r
         /*\r
          * SignatureTime\r
          */\r
@@ -233,22 +209,21 @@ public class OOXMLSignatureFacet implements SignatureFacet {
         Element n = (Element)document.importNode(ctTime.getDomNode(),true);\r
         List<XMLStructure> signatureTimeContent = new ArrayList<XMLStructure>();\r
         signatureTimeContent.add(new DOMStructure(n));\r
-        SignatureProperty signatureTimeSignatureProperty = signatureFactory\r
+        SignatureProperty signatureTimeSignatureProperty = getSignatureFactory()\r
             .newSignatureProperty(signatureTimeContent, "#" + signatureConfig.getPackageSignatureId(),\r
             "idSignatureTime");\r
         List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();\r
         signaturePropertyContent.add(signatureTimeSignatureProperty);\r
-        SignatureProperties signatureProperties = signatureFactory\r
+        SignatureProperties signatureProperties = getSignatureFactory()\r
             .newSignatureProperties(signaturePropertyContent,\r
             "id-signature-time-" + signatureConfig.getExecutionTime());\r
         objectContent.add(signatureProperties);\r
     }\r
 \r
     protected void addSignatureInfo(Document document,\r
-        XMLSignatureFactory signatureFactory,\r
         List<Reference> references,\r
         List<XMLObject> objects)\r
-    throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
+    throws XMLSignatureException {\r
         List<XMLStructure> objectContent = new ArrayList<XMLStructure>();\r
 \r
         SignatureInfoV1Document sigV1 = SignatureInfoV1Document.Factory.newInstance();\r
@@ -259,31 +234,23 @@ public class OOXMLSignatureFacet implements SignatureFacet {
         \r
         List<XMLStructure> signatureInfoContent = new ArrayList<XMLStructure>();\r
         signatureInfoContent.add(new DOMStructure(n));\r
-        SignatureProperty signatureInfoSignatureProperty = signatureFactory\r
+        SignatureProperty signatureInfoSignatureProperty = getSignatureFactory()\r
             .newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(),\r
             "idOfficeV1Details");\r
 \r
         List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();\r
         signaturePropertyContent.add(signatureInfoSignatureProperty);\r
-        SignatureProperties signatureProperties = signatureFactory\r
+        SignatureProperties signatureProperties = getSignatureFactory()\r
             .newSignatureProperties(signaturePropertyContent, null);\r
         objectContent.add(signatureProperties);\r
 \r
         String objectId = "idOfficeObject";\r
-        objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));\r
+        objects.add(getSignatureFactory().newXMLObject(objectContent, objectId, null, null));\r
 \r
-        DigestMethod digestMethod = signatureFactory.newDigestMethod\r
-            (signatureConfig.getDigestMethodUri(), null);\r
-        Reference reference = signatureFactory.newReference\r
-            ("#" + objectId, digestMethod, null, XML_DIGSIG_NS+"Object", null);\r
+        Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS+"Object", null, null);\r
         references.add(reference);\r
     }\r
 \r
-    @Override\r
-    public void postSign(Document document) {\r
-        // empty\r
-    }\r
-\r
     protected static String getRelationshipReferenceURI(String zipEntryName) {\r
         return "/"\r
             + zipEntryName\r
index 7caf28d2db45a561e1e6fbc06fc49d8bf92aa6ed..2cdfe0f671e0151cf4799f35c374ebb289d595d3 100644 (file)
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.security.InvalidAlgorithmParameterException;\r
-import java.security.NoSuchAlgorithmException;\r
-import java.util.List;\r
+import javax.xml.crypto.MarshalException;\r
 \r
-import javax.xml.crypto.dsig.Reference;\r
-import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
-\r
-import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
 import org.apache.xmlbeans.XmlException;\r
 import org.etsi.uri.x01903.v13.QualifyingPropertiesType;\r
 import org.etsi.uri.x01903.v13.UnsignedPropertiesType;\r
@@ -50,32 +43,23 @@ import org.w3c.dom.NodeList;
  * @author Frank Cornelis\r
  * \r
  */\r
-public class Office2010SignatureFacet implements SignatureFacet {\r
-\r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-        // this.signatureConfig = signatureConfig;\r
-    }\r
-    \r
-    @Override\r
-    public void preSign(\r
-          Document document\r
-        , XMLSignatureFactory signatureFactory\r
-        , List<Reference> references\r
-        , List<XMLObject> objects\r
-    ) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
-    }\r
+public class Office2010SignatureFacet extends SignatureFacet {\r
 \r
     @Override\r
     public void postSign(Document document)\r
-    throws XmlException {\r
+    throws MarshalException {\r
         // check for XAdES-BES\r
         NodeList nl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");\r
         if (nl.getLength() != 1) {\r
-            throw new IllegalArgumentException("no XAdES-BES extension present");\r
+            throw new MarshalException("no XAdES-BES extension present");\r
         }\r
 \r
-        QualifyingPropertiesType qualProps =\r
-                QualifyingPropertiesType.Factory.parse(nl.item(0));\r
+        QualifyingPropertiesType qualProps;\r
+        try {\r
+            qualProps = QualifyingPropertiesType.Factory.parse(nl.item(0));\r
+        } catch (XmlException e) {\r
+            throw new MarshalException(e);\r
+        }\r
         \r
         // create basic XML container structure\r
         UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();\r
index 4954f04cbc7d2728e348a715da73ff6ad7e47a8e..58507274ee6df58279baca4fd1a371305f445c82 100644 (file)
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.io.IOException;\r
-import java.net.URISyntaxException;\r
-import java.security.InvalidAlgorithmParameterException;\r
-import java.security.NoSuchAlgorithmException;\r
+import java.security.GeneralSecurityException;\r
 import java.util.List;\r
 \r
 import javax.xml.XMLConstants;\r
 import javax.xml.crypto.MarshalException;\r
+import javax.xml.crypto.dsig.DigestMethod;\r
 import javax.xml.crypto.dsig.Reference;\r
+import javax.xml.crypto.dsig.Transform;\r
 import javax.xml.crypto.dsig.XMLObject;\r
 import javax.xml.crypto.dsig.XMLSignature;\r
+import javax.xml.crypto.dsig.XMLSignatureException;\r
 import javax.xml.crypto.dsig.XMLSignatureFactory;\r
+import javax.xml.crypto.dsig.spec.TransformParameterSpec;\r
 \r
 import org.apache.poi.openxml4j.opc.PackageNamespaces;\r
+import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
 import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable;\r
-import org.apache.xmlbeans.XmlException;\r
 import org.w3c.dom.Document;\r
 \r
 /**\r
- * JSR105 Signature Facet interface.\r
- * \r
- * @author Frank Cornelis\r
- * \r
+ * JSR105 Signature Facet base class.\r
  */\r
-public interface SignatureFacet extends SignatureConfigurable {\r
+public abstract class SignatureFacet implements SignatureConfigurable {\r
 \r
-    String XML_NS = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;\r
-    String XML_DIGSIG_NS = XMLSignature.XMLNS;\r
-    String OO_DIGSIG_NS = PackageNamespaces.DIGITAL_SIGNATURE;\r
-    String MS_DIGSIG_NS = "http://schemas.microsoft.com/office/2006/digsig";\r
-    String XADES_132_NS = "http://uri.etsi.org/01903/v1.3.2#";\r
-    String XADES_141_NS = "http://uri.etsi.org/01903/v1.4.1#";\r
+    public static final String XML_NS = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;\r
+    public static final String XML_DIGSIG_NS = XMLSignature.XMLNS;\r
+    public static final String OO_DIGSIG_NS = PackageNamespaces.DIGITAL_SIGNATURE;\r
+    public static final String MS_DIGSIG_NS = "http://schemas.microsoft.com/office/2006/digsig";\r
+    public static final String XADES_132_NS = "http://uri.etsi.org/01903/v1.3.2#";\r
+    public static final String XADES_141_NS = "http://uri.etsi.org/01903/v1.4.1#";\r
 \r
+    protected SignatureConfig signatureConfig;\r
+    protected ThreadLocal<XMLSignatureFactory> signatureFactory;\r
+\r
+    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
+        this.signatureConfig = signatureConfig;\r
+    }\r
 \r
     /**\r
      * This method is being invoked by the XML signature service engine during\r
@@ -64,21 +68,17 @@ public interface SignatureFacet extends SignatureConfigurable {
      * signature facets to an XML signature.\r
      * \r
      * @param document the signature document to be used for imports\r
-     * @param signatureFactory the signature factory\r
      * @param references list of reference definitions\r
      * @param objects objects to be signed/included in the signature document\r
-     * @throws NoSuchAlgorithmException\r
-     * @throws InvalidAlgorithmParameterException\r
-     * @throws IOException\r
-     * @throws URISyntaxException\r
-     * @throws XmlException\r
+     * @throws XMLSignatureException\r
      */\r
-    void preSign(\r
+    public void preSign(\r
           Document document\r
-        , XMLSignatureFactory signatureFactory\r
         , List<Reference> references\r
         , List<XMLObject> objects\r
-    ) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, URISyntaxException, XmlException;\r
+    ) throws XMLSignatureException {\r
+        // empty\r
+    }\r
 \r
     /**\r
      * This method is being invoked by the XML signature service engine during\r
@@ -87,9 +87,59 @@ public interface SignatureFacet extends SignatureConfigurable {
      *\r
      * @param document the signature document to be modified\r
      * @throws MarshalException\r
-     * @throws XmlException\r
      */\r
-    void postSign(\r
-          Document document\r
-    ) throws MarshalException, XmlException;\r
+    public void postSign(Document document) throws MarshalException {\r
+        // empty\r
+    }\r
+\r
+    protected XMLSignatureFactory getSignatureFactory() {\r
+        return signatureConfig.getSignatureFactory();\r
+    }\r
+    \r
+    protected Transform newTransform(String canonicalizationMethod) throws XMLSignatureException {\r
+        return newTransform(canonicalizationMethod, null);\r
+    }\r
+    \r
+    protected Transform newTransform(String canonicalizationMethod, TransformParameterSpec paramSpec)\r
+    throws XMLSignatureException {\r
+        try {\r
+            return getSignatureFactory().newTransform(canonicalizationMethod, paramSpec);\r
+        } catch (GeneralSecurityException e) {\r
+            throw new XMLSignatureException("unknown canonicalization method: "+canonicalizationMethod, e);\r
+        }\r
+    }\r
+    \r
+    protected Reference newReference(String uri, List<Transform> transforms, String type, String id, byte digestValue[])\r
+    throws XMLSignatureException {\r
+        return newReference(uri, transforms, type, id, digestValue, signatureConfig);\r
+    }\r
+\r
+    public static Reference newReference(\r
+          String uri\r
+        , List<Transform> transforms\r
+        , String type\r
+        , String id\r
+        , byte digestValue[]\r
+        , SignatureConfig signatureConfig)\r
+    throws XMLSignatureException {\r
+        // the references appear in the package signature or the package object\r
+        // so we can use the default digest algorithm\r
+        String digestMethodUri = signatureConfig.getDigestMethodUri();\r
+        XMLSignatureFactory sigFac = signatureConfig.getSignatureFactory();\r
+        DigestMethod digestMethod;\r
+        try {\r
+            digestMethod = sigFac.newDigestMethod(digestMethodUri, null);\r
+        } catch (GeneralSecurityException e) {\r
+            throw new XMLSignatureException("unknown digest method uri: "+digestMethodUri, e);\r
+        }\r
+\r
+        Reference reference;\r
+        if (digestValue == null) {\r
+            reference = sigFac.newReference(uri, digestMethod, transforms, type, id);\r
+        } else {\r
+            reference = sigFac.newReference(uri, digestMethod, transforms, type, id, digestValue);\r
+        }\r
+\r
+        return reference;\r
+    }\r
 }
\ No newline at end of file
index 4163cbcb79ebe21663401e51d7656e9c939b5519..c14fb38340216a72263e4a82ac7001728d0d476f 100644 (file)
@@ -24,9 +24,7 @@
 \r
 package org.apache.poi.poifs.crypt.dsig.facets;\r
 \r
-import java.security.InvalidAlgorithmParameterException;\r
 import java.security.MessageDigest;\r
-import java.security.NoSuchAlgorithmException;\r
 import java.security.cert.CertificateEncodingException;\r
 import java.security.cert.X509Certificate;\r
 import java.util.ArrayList;\r
@@ -39,12 +37,10 @@ import java.util.TimeZone;
 import javax.xml.crypto.XMLStructure;\r
 import javax.xml.crypto.dom.DOMStructure;\r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
-import javax.xml.crypto.dsig.DigestMethod;\r
 import javax.xml.crypto.dsig.Reference;\r
 import javax.xml.crypto.dsig.Transform;\r
 import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
-import javax.xml.crypto.dsig.spec.TransformParameterSpec;\r
+import javax.xml.crypto.dsig.XMLSignatureException;\r
 \r
 import org.apache.poi.poifs.crypt.CryptoFunctions;\r
 import org.apache.poi.poifs.crypt.HashAlgorithm;\r
@@ -89,30 +85,21 @@ import org.w3c.dom.Element;
  * @see <a href="http://en.wikipedia.org/wiki/XAdES">XAdES</a>\r
  * \r
  */\r
-public class XAdESSignatureFacet implements SignatureFacet {\r
+public class XAdESSignatureFacet extends SignatureFacet {\r
 \r
     private static final POILogger LOG = POILogFactory.getLogger(XAdESSignatureFacet.class);\r
 \r
     private static final String XADES_TYPE = "http://uri.etsi.org/01903#SignedProperties";\r
     \r
-    private SignatureConfig signatureConfig;\r
-    \r
     private Map<String, String> dataObjectFormatMimeTypes = new HashMap<String, String>();\r
 \r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-        this.signatureConfig = signatureConfig;\r
-    }\r
-\r
-    @Override\r
-    public void postSign(Document document) {\r
-        LOG.log(POILogger.DEBUG, "postSign");\r
-    }\r
 \r
     @Override\r
-    public void preSign(Document document,\r
-            XMLSignatureFactory signatureFactory,\r
-            List<Reference> references, List<XMLObject> objects)\r
-            throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
+    public void preSign(\r
+          Document document\r
+        , List<Reference> references\r
+        , List<XMLObject> objects)\r
+    throws XMLSignatureException {\r
         LOG.log(POILogger.DEBUG, "preSign");\r
 \r
         // QualifyingProperties\r
@@ -209,18 +196,15 @@ public class XAdESSignatureFacet implements SignatureFacet {
         Element qualDocElSrc = (Element)qualifyingProperties.getDomNode();\r
         Element qualDocEl = (Element)document.importNode(qualDocElSrc, true);\r
         xadesObjectContent.add(new DOMStructure(qualDocEl));\r
-        XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null);\r
+        XMLObject xadesObject = getSignatureFactory().newXMLObject(xadesObjectContent, null, null, null);\r
         objects.add(xadesObject);\r
 \r
         // add XAdES ds:Reference\r
-        DigestMethod digestMethod = signatureFactory.newDigestMethod(signatureConfig.getDigestMethodUri(), null);\r
         List<Transform> transforms = new ArrayList<Transform>();\r
-        Transform exclusiveTransform = signatureFactory\r
-                .newTransform(CanonicalizationMethod.INCLUSIVE,\r
-                        (TransformParameterSpec) null);\r
+        Transform exclusiveTransform = newTransform(CanonicalizationMethod.INCLUSIVE);\r
         transforms.add(exclusiveTransform);\r
-        Reference reference = signatureFactory.newReference\r
-            ("#"+signatureConfig.getXadesSignatureId(), digestMethod, transforms, XADES_TYPE, null);\r
+        Reference reference = newReference\r
+            ("#"+signatureConfig.getXadesSignatureId(), transforms, XADES_TYPE, null, null);\r
         references.add(reference);\r
     }\r
 \r
index 62572939b54df27abea04e2829ec671c04396b4e..b092f1c09136baeceeaca52399e96aef2eeb607f 100644 (file)
@@ -29,8 +29,6 @@ import static org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet.insertX
 import java.io.ByteArrayInputStream;\r
 import java.io.ByteArrayOutputStream;\r
 import java.math.BigInteger;\r
-import java.security.InvalidAlgorithmParameterException;\r
-import java.security.NoSuchAlgorithmException;\r
 import java.security.cert.CRLException;\r
 import java.security.cert.CertificateEncodingException;\r
 import java.security.cert.CertificateException;\r
@@ -43,12 +41,9 @@ import java.util.Collections;
 import java.util.List;\r
 import java.util.UUID;\r
 \r
+import javax.xml.crypto.MarshalException;\r
 import javax.xml.crypto.dsig.CanonicalizationMethod;\r
-import javax.xml.crypto.dsig.Reference;\r
-import javax.xml.crypto.dsig.XMLObject;\r
-import javax.xml.crypto.dsig.XMLSignatureFactory;\r
 \r
-import org.apache.poi.poifs.crypt.dsig.SignatureConfig;\r
 import org.apache.poi.poifs.crypt.dsig.services.RevocationData;\r
 import org.apache.poi.util.POILogFactory;\r
 import org.apache.poi.util.POILogger;\r
@@ -106,20 +101,14 @@ import org.w3c.dom.NodeList;
  * @author Frank Cornelis\r
  * @see XAdESSignatureFacet\r
  */\r
-public class XAdESXLSignatureFacet implements SignatureFacet {\r
+public class XAdESXLSignatureFacet extends SignatureFacet {\r
 \r
     private static final POILogger LOG = POILogFactory.getLogger(XAdESXLSignatureFacet.class);\r
 \r
-    private SignatureConfig signatureConfig;\r
-\r
     private String c14nAlgoId = CanonicalizationMethod.EXCLUSIVE;\r
 \r
     private final CertificateFactory certificateFactory;\r
 \r
-    public void setSignatureConfig(SignatureConfig signatureConfig) {\r
-         this.signatureConfig = signatureConfig;\r
-    }\r
-    \r
     public XAdESXLSignatureFacet() {\r
         try {\r
             this.certificateFactory = CertificateFactory.getInstance("X.509");\r
@@ -133,7 +122,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
     }\r
 \r
     @Override\r
-    public void postSign(Document document) throws XmlException {\r
+    public void postSign(Document document) throws MarshalException {\r
         LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");\r
 \r
         QualifyingPropertiesDocument qualDoc = null;\r
@@ -142,10 +131,14 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
         // check for XAdES-BES\r
         NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");\r
         if (qualNl.getLength() == 1) {\r
-            qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0));\r
+            try {\r
+                qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0));\r
+            } catch (XmlException e) {\r
+                throw new MarshalException(e);\r
+            }\r
             qualProps = qualDoc.getQualifyingProperties();\r
         } else {\r
-            throw new IllegalArgumentException("no XAdES-BES extension present");\r
+            throw new MarshalException("no XAdES-BES extension present");\r
         }\r
 \r
         // create basic XML container structure\r
@@ -335,14 +328,6 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
         return c14nValue.toByteArray();\r
     }\r
 \r
-    @Override\r
-    public void preSign(Document document,\r
-            XMLSignatureFactory signatureFactory,\r
-            List<Reference> references, List<XMLObject> objects)\r
-            throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {\r
-        // nothing to do here\r
-    }\r
-\r
     private BigInteger getCrlNumber(X509CRL crl) {\r
         try {\r
             byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId());\r