You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@santuario.apache.org by co...@apache.org on 2012/02/21 11:16:01 UTC

svn commit: r1291689 - in /santuario/xml-security-java/trunk: ./ src/main/java/org/apache/xml/security/encryption/

Author: coheigea
Date: Tue Feb 21 10:16:00 2012
New Revision: 1291689

URL: http://svn.apache.org/viewvc?rev=1291689&view=rev
Log:
[SANTUARIO-300] - decryption/encryption optimization
 - Patch applied, thanks.
 - I added similar functionalty for the TransformSerializer and refactored some duplicate code

Modified:
    santuario/xml-security-java/trunk/CHANGELOG.txt
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/AbstractSerializer.java
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/Serializer.java
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/TransformSerializer.java
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/XMLCipher.java

Modified: santuario/xml-security-java/trunk/CHANGELOG.txt
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/CHANGELOG.txt?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/CHANGELOG.txt (original)
+++ santuario/xml-security-java/trunk/CHANGELOG.txt Tue Feb 21 10:16:00 2012
@@ -1,6 +1,7 @@
 Changelog for "Apache xml-security" <http://santuario.apache.org/>
 
 New in v1.5.1-SNAPSHOT:
+    Fixed SANTUARIO-300 - decryption/encryption optimization.
     Fixed SANTUARIO-296 - XMLSignatureInput fails with an IOException if constructed on a BufferedInputStream
     Fixed SANTUARIO-298 - Xalan is still a required dependency
     Fixed SANTUARIO-299 - StringIndexOutOfBoundsException is thrown during reference verification (if URI = "#")

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/AbstractSerializer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/AbstractSerializer.java?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/AbstractSerializer.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/AbstractSerializer.java Tue Feb 21 10:16:00 2012
@@ -19,6 +19,9 @@
 package org.apache.xml.security.encryption;
 
 import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -57,6 +60,19 @@ public abstract class AbstractSerializer
     }
 
     /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>Element</code>.
+     *
+     * @param element the <code>Element</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serilaized
+     *   <code>Element</code>.
+     * @throws Exception
+     */
+    public byte[] serializeToByteArray(Element element) throws Exception {
+        return canonSerializeToByteArray(element);
+    }
+
+    /**
      * Returns a <code>String</code> representation of the specified
      * <code>NodeList</code>.
      * <p/>
@@ -91,6 +107,25 @@ public abstract class AbstractSerializer
     }
 
     /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>NodeList</code>.
+     * 
+     * @param content the <code>NodeList</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serialized
+     *   <code>NodeList</code>.
+     * @throws Exception
+     */
+    public byte[] serializeToByteArray(NodeList content) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        for (int i = 0; i < content.getLength(); i++) {
+            canon.canonicalizeSubtree(content.item(i));
+        }
+        return baos.toByteArray();
+    }
+
+    /**
      * Use the Canonicalizer to serialize the node
      * @param node
      * @return the canonicalization of the node
@@ -107,12 +142,78 @@ public abstract class AbstractSerializer
     }
 
     /**
+     * Use the Canonicalizer to serialize the node
+     * @param node
+     * @return the (byte[]) canonicalization of the node
+     * @throws Exception
+     */ 
+    public byte[] canonSerializeToByteArray(Node node) throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        canon.setWriter(baos);
+        canon.notReset();
+        canon.canonicalizeSubtree(node);
+        return baos.toByteArray();
+    }
+
+    /**
      * @param source
      * @param ctx
      * @return the Node resulting from the parse of the source
      * @throws XMLEncryptionException
      */
     public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
+
+    protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException {
+        // Create the context to parse the document against
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        try {
+            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
+            outputStreamWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
+
+            // Run through each node up to the document node and find any xmlns: nodes
+            Map<String, String> storedNamespaces = new HashMap<String, String>();
+            Node wk = ctx;
+            while (wk != null) {
+                NamedNodeMap atts = wk.getAttributes();
+                if (atts != null) {
+                    for (int i = 0; i < atts.getLength(); ++i) {
+                        Node att = atts.item(i);
+                        String nodeName = att.getNodeName();
+                        if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
+                                && !storedNamespaces.containsKey(att.getNodeName())) {
+                            outputStreamWriter.write(" ");
+                            outputStreamWriter.write(nodeName);
+                            outputStreamWriter.write("=\"");
+                            outputStreamWriter.write(att.getNodeValue());
+                            outputStreamWriter.write("\"");
+                            storedNamespaces.put(nodeName, att.getNodeValue());
+                        }
+                    }
+                }
+                wk = wk.getParentNode();
+            }
+            outputStreamWriter.write(">");
+            outputStreamWriter.flush();
+            byteArrayOutputStream.write(source);
+
+            outputStreamWriter.write("</dummy>");
+            outputStreamWriter.close();
+
+            return byteArrayOutputStream.toByteArray();
+        } catch (UnsupportedEncodingException e) {
+            throw new XMLEncryptionException("empty", e);
+        } catch (IOException e) {
+            throw new XMLEncryptionException("empty", e);
+        }
+    }
     
     protected static String createContext(String source, Node ctx) {
         // Create the context to parse the document against

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/DocumentSerializer.java Tue Feb 21 10:16:00 2012
@@ -18,6 +18,7 @@
  */
 package org.apache.xml.security.encryption;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.StringReader;
 
@@ -39,6 +40,17 @@ import org.xml.sax.SAXException;
 public class DocumentSerializer extends AbstractSerializer {
     
     protected DocumentBuilderFactory dbf;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException {
+        byte[] fragment = createContext(source, ctx);
+        return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment)));
+    }
     
     /**
      * @param source
@@ -48,7 +60,16 @@ public class DocumentSerializer extends 
      */
     public Node deserialize(String source, Node ctx) throws XMLEncryptionException {
         String fragment = createContext(source, ctx);
-        
+        return deserialize(ctx, new InputSource(new StringReader(fragment)));
+    }
+    
+    /**
+     * @param ctx
+     * @param inputSource
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException {
         try {
             if (dbf == null) {
                 dbf = DocumentBuilderFactory.newInstance();
@@ -58,17 +79,17 @@ public class DocumentSerializer extends 
                 dbf.setValidating(false);
             }
             DocumentBuilder db = dbf.newDocumentBuilder();
-            Document d = db.parse(new InputSource(new StringReader(fragment)));
-            
+            Document d = db.parse(inputSource);
+
             Document contextDocument = null;
             if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
                 contextDocument = (Document)ctx;
             } else {
                 contextDocument = ctx.getOwnerDocument();
             }
-            
-            Element fragElt = 
-                (Element) contextDocument.importNode(d.getDocumentElement(), true);
+
+            Element fragElt =
+                    (Element) contextDocument.importNode(d.getDocumentElement(), true);
             DocumentFragment result = contextDocument.createDocumentFragment();
             Node child = fragElt.getFirstChild();
             while (child != null) {

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/Serializer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/Serializer.java?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/Serializer.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/Serializer.java Tue Feb 21 10:16:00 2012
@@ -42,9 +42,21 @@ public interface Serializer {
      *   <code>Element</code>.
      * @throws Exception
      */
+    @Deprecated
     String serialize(Element element) throws Exception;
 
     /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>Element</code>.
+     *
+     * @param element the <code>Element</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serilaized
+     *   <code>Element</code>.
+     * @throws Exception
+     */
+    byte[] serializeToByteArray(Element element) throws Exception;
+
+    /**
      * Returns a <code>String</code> representation of the specified
      * <code>NodeList</code>.
      * 
@@ -53,21 +65,51 @@ public interface Serializer {
      *   <code>NodeList</code>.
      * @throws Exception
      */
+    @Deprecated
     String serialize(NodeList content) throws Exception;
 
     /**
+     * Returns a <code>byte[]</code> representation of the specified
+     * <code>NodeList</code>.
+     * 
+     * @param content the <code>NodeList</code> to serialize.
+     * @return the <code>byte[]</code> representation of the serialized
+     *   <code>NodeList</code>.
+     * @throws Exception
+     */
+    byte[] serializeToByteArray(NodeList content) throws Exception;
+
+    /**
      * Use the Canonicalizer to serialize the node
      * @param node
      * @return the canonicalization of the node
      * @throws Exception
-     */ 
+     */
+    @Deprecated
     String canonSerialize(Node node) throws Exception;
 
     /**
+     * Use the Canonicalizer to serialize the node
+     * @param node
+     * @return the (byte[]) canonicalization of the node
+     * @throws Exception
+     */ 
+    byte[] canonSerializeToByteArray(Node node) throws Exception;
+
+    /**
      * @param source
      * @param ctx
      * @return the Node resulting from the parse of the source
      * @throws XMLEncryptionException
      */
+    @Deprecated
     Node deserialize(String source, Node ctx) throws XMLEncryptionException;
-}
\ No newline at end of file
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
+}

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/TransformSerializer.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/TransformSerializer.java?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/TransformSerializer.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/TransformSerializer.java Tue Feb 21 10:16:00 2012
@@ -18,6 +18,7 @@
  */
 package org.apache.xml.security.encryption;
 
+import java.io.ByteArrayInputStream;
 import java.io.StringReader;
 
 import javax.xml.XMLConstants;
@@ -38,6 +39,17 @@ import org.w3c.dom.Node;
 public class TransformSerializer extends AbstractSerializer {
     
     private TransformerFactory transformerFactory;
+
+    /**
+     * @param source
+     * @param ctx
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException {
+        byte[] fragment = createContext(source, ctx);
+        return deserialize(ctx, new StreamSource(new ByteArrayInputStream(fragment)));
+    }
     
     /**
      * @param source
@@ -47,7 +59,16 @@ public class TransformSerializer extends
      */
     public Node deserialize(String source, Node ctx) throws XMLEncryptionException {
         String fragment = createContext(source, ctx);
-        
+        return deserialize(ctx, new StreamSource(new StringReader(fragment)));
+    }
+    
+    /**
+     * @param ctx
+     * @param source
+     * @return the Node resulting from the parse of the source
+     * @throws XMLEncryptionException
+     */
+    private Node deserialize(Node ctx, Source source) throws XMLEncryptionException {
         try {
             Document contextDocument = null;
             if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
@@ -55,7 +76,6 @@ public class TransformSerializer extends
             } else {
                 contextDocument = ctx.getOwnerDocument();
             }
-            Source src = new StreamSource(new StringReader(fragment));
             
             if (transformerFactory == null) {
                 transformerFactory = TransformerFactory.newInstance();
@@ -68,7 +88,7 @@ public class TransformSerializer extends
             Node placeholder = contextDocument.createDocumentFragment();
             res.setNode(placeholder);
 
-            transformer.transform(src, res);
+            transformer.transform(source, res);
 
             // Skip dummy element
             Node dummyChild = placeholder.getFirstChild();

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/XMLCipher.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/XMLCipher.java?rev=1291689&r1=1291688&r2=1291689&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/XMLCipher.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/encryption/XMLCipher.java Tue Feb 21 10:16:00 2012
@@ -1039,18 +1039,18 @@ public class XMLCipher {
             throw new XMLEncryptionException("XMLCipher instance without transformation specified");
         }
 
-        String serializedOctets = null;
+        byte[] serializedOctets = null;
         if (serializedData == null) {
             if (type.equals(EncryptionConstants.TYPE_CONTENT)) {
                 NodeList children = element.getChildNodes();
                 if (null != children) {
-                    serializedOctets = serializer.serialize(children);
+                    serializedOctets = serializer.serializeToByteArray(children);
                 } else {
                     Object exArgs[] = { "Element has no content." };
                     throw new XMLEncryptionException("empty", exArgs);
                 }
             } else {
-                serializedOctets = serializer.serialize(element);
+                serializedOctets = serializer.serializeToByteArray(element);
             }
             if (log.isDebugEnabled()) {
                 log.debug("Serialized octets:\n" + serializedOctets);
@@ -1100,10 +1100,10 @@ public class XMLCipher {
                 baos.write(c.doFinal());
                 encryptedBytes = baos.toByteArray();
             } else {
-                encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8"));
+                encryptedBytes = c.doFinal(serializedOctets);
                 if (log.isDebugEnabled()) {
                     log.debug("Expected cipher.outputSize = " +
-                        Integer.toString(c.getOutputSize(serializedOctets.getBytes("UTF-8").length)));
+                        Integer.toString(c.getOutputSize(serializedOctets.length)));
                 }
             }
             if (log.isDebugEnabled()) {
@@ -1555,12 +1555,7 @@ public class XMLCipher {
             log.error("XMLCipher unexpectedly not in DECRYPT_MODE...");
         }
 
-        String octets;
-        try {
-            octets = new String(decryptToByteArray(element), "UTF-8");
-        } catch (UnsupportedEncodingException uee) {
-            throw new XMLEncryptionException("empty", uee);
-        }
+        byte[] octets = decryptToByteArray(element);
 
         if (log.isDebugEnabled()) {
             log.debug("Decrypted octets:\n" + octets);