You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@santuario.apache.org by gi...@apache.org on 2014/04/21 15:35:59 UTC

svn commit: r1588881 - in /santuario/xml-security-java/trunk/src: main/java/org/apache/xml/security/stax/impl/processor/input/ main/java/org/apache/xml/security/stax/impl/processor/output/ test/java/org/apache/xml/security/test/stax/signature/

Author: giger
Date: Mon Apr 21 13:35:59 2014
New Revision: 1588881

URL: http://svn.apache.org/r1588881
Log:
make it possible to process signed and encrypted documents in one pass.

Modified:
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java
    santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/output/XMLEncryptOutputProcessor.java
    santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/signature/SignatureEncryptionTest.java

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java?rev=1588881&r1=1588880&r2=1588881&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java Mon Apr 21 13:35:59 2014
@@ -18,13 +18,6 @@
  */
 package org.apache.xml.security.stax.impl.processor.input;
 
-import java.util.ArrayDeque;
-
-import javax.xml.stream.XMLStreamConstants;
-import javax.xml.stream.XMLStreamException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.apache.xml.security.exceptions.XMLSecurityException;
 import org.apache.xml.security.stax.ext.AbstractInputProcessor;
 import org.apache.xml.security.stax.ext.InputProcessorChain;
@@ -34,6 +27,10 @@ import org.apache.xml.security.stax.ext.
 import org.apache.xml.security.stax.ext.stax.XMLSecEvent;
 import org.apache.xml.security.stax.ext.stax.XMLSecStartElement;
 
+import javax.xml.stream.XMLStreamConstants;
+import javax.xml.stream.XMLStreamException;
+import java.util.ArrayDeque;
+
 /**
  * Processor for XML Security.
  *
@@ -42,11 +39,10 @@ import org.apache.xml.security.stax.ext.
  */
 public class XMLSecurityInputProcessor extends AbstractInputProcessor {
 
-    protected static final transient Logger logger = LoggerFactory.getLogger(XMLSecurityInputProcessor.class);
-
-    private final ArrayDeque<XMLSecEvent> xmlSecEventList = new ArrayDeque<XMLSecEvent>();
-    private int eventCount = 0;
     private int startIndexForProcessor = 0;
+    private InternalBufferProcessor internalBufferProcessor;
+    private boolean signatureElementFound = false;
+    private boolean encryptedDataElementFound = false;
 
     public XMLSecurityInputProcessor(XMLSecurityProperties securityProperties) {
         super(securityProperties);
@@ -63,98 +59,103 @@ public class XMLSecurityInputProcessor e
     public XMLSecEvent processNextEvent(InputProcessorChain inputProcessorChain)
             throws XMLStreamException, XMLSecurityException {
 
-        //buffer all events until the end of the required actions
-        final InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);
-        final InternalBufferProcessor internalBufferProcessor
-                = new InternalBufferProcessor(getSecurityProperties());
-        subInputProcessorChain.addProcessor(internalBufferProcessor);
-
-        boolean signatureElementFound = false;
-
-        XMLSecEvent xmlSecEvent;
-        do {
-            subInputProcessorChain.reset();
-            xmlSecEvent = subInputProcessorChain.processHeaderEvent();
-            eventCount++;
-
-            switch (xmlSecEvent.getEventType()) {
-                case XMLStreamConstants.START_ELEMENT:
-                    final XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();
-
-                    if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
+        //add the buffer processor (for signature) when this processor is called for the first time
+        if (internalBufferProcessor == null) {
+            internalBufferProcessor = new InternalBufferProcessor(getSecurityProperties());
+            inputProcessorChain.addProcessor(internalBufferProcessor);
+        }
+
+        XMLSecEvent xmlSecEvent = inputProcessorChain.processEvent();
+        switch (xmlSecEvent.getEventType()) {
+            case XMLStreamConstants.START_ELEMENT:
+                final XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();
+
+                if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
+                    signatureElementFound = true;
+                    startIndexForProcessor = internalBufferProcessor.getXmlSecEventList().size() - 1;
+                } else if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
+                    encryptedDataElementFound = true;
+
+                    XMLDecryptInputProcessor decryptInputProcessor = new XMLDecryptInputProcessor(getSecurityProperties());
+                    decryptInputProcessor.setPhase(XMLSecurityConstants.Phase.PREPROCESSING);
+                    decryptInputProcessor.addAfterProcessor(XMLEventReaderInputProcessor.class.getName());
+                    decryptInputProcessor.addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
+                    decryptInputProcessor.addBeforeProcessor(XMLSecurityInputProcessor.InternalBufferProcessor.class.getName());
+                    inputProcessorChain.addProcessor(decryptInputProcessor);
+
+                    final ArrayDeque<XMLSecEvent> xmlSecEventList = internalBufferProcessor.getXmlSecEventList();
+                    //remove the last event (EncryptedData)
+                    xmlSecEventList.pollFirst();
+
+                    // temporary processor to return the EncryptedData element for the DecryptionProcessor
+                    AbstractInputProcessor abstractInputProcessor = new AbstractInputProcessor(getSecurityProperties()) {
+                        @Override
+                        public XMLSecEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain)
+                                throws XMLStreamException, XMLSecurityException {
+                            return processNextEvent(inputProcessorChain);
+                        }
+
+                        @Override
+                        public XMLSecEvent processNextEvent(InputProcessorChain inputProcessorChain)
+                                throws XMLStreamException, XMLSecurityException {
+                            inputProcessorChain.removeProcessor(this);
+                            return xmlSecStartElement;
+                        }
+                    };
+                    abstractInputProcessor.setPhase(XMLSecurityConstants.Phase.PREPROCESSING);
+                    abstractInputProcessor.addBeforeProcessor(decryptInputProcessor);
+                    inputProcessorChain.addProcessor(abstractInputProcessor);
+
+                    //fetch the next event from the original chain
+                    inputProcessorChain.reset();
+                    xmlSecEvent = inputProcessorChain.processEvent();
+
+                    //check if the decrypted element is a Signature element
+                    if (xmlSecEvent.isStartElement() &&
+                            xmlSecEvent.asStartElement().getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
                         signatureElementFound = true;
-                        startIndexForProcessor = eventCount - 1;
-                    } else if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
-                        XMLDecryptInputProcessor inputProcessor = new XMLDecryptInputProcessor(getSecurityProperties());
-                        subInputProcessorChain.addProcessor(inputProcessor);
-
-                        subInputProcessorChain.removeProcessor(internalBufferProcessor);
-                        InternalReplayProcessor internalReplayProcessor = new InternalReplayProcessor(getSecurityProperties());
-                        internalReplayProcessor.setPhase(XMLSecurityConstants.Phase.PROCESSING);
-                        internalReplayProcessor.getAfterProcessors().clear();
-                        internalReplayProcessor.getBeforeProcessors().clear();
-                        internalReplayProcessor.addAfterProcessor(XMLDecryptInputProcessor.class.getName());
-                        subInputProcessorChain.addProcessor(internalReplayProcessor);
-
-                        AbstractInputProcessor abstractInputProcessor = new AbstractInputProcessor(getSecurityProperties()) {
-                            @Override
-                            public XMLSecEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, XMLSecurityException {
-                                return null;
-                            }
-
-                            @Override
-                            public XMLSecEvent processNextEvent(InputProcessorChain inputProcessorChain) throws XMLStreamException, XMLSecurityException {
-                                inputProcessorChain.removeProcessor(this);
-                                return xmlSecStartElement;
-                            }
-                        };
-                        abstractInputProcessor.setPhase(XMLSecurityConstants.Phase.PREPROCESSING);
-                        abstractInputProcessor.addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
-                        abstractInputProcessor.addAfterProcessor(XMLEventReaderInputProcessor.class.getName());
-                        subInputProcessorChain.addProcessor(abstractInputProcessor);
-
-                        //remove this processor from chain now. the next events will go directly to the other processors
-                        subInputProcessorChain.removeProcessor(this);
-                        //since we cloned the inputProcessor list we have to add the processors from
-                        //the subChain to the main chain.
-                        inputProcessorChain.getProcessors().clear();
-                        inputProcessorChain.getProcessors().addAll(subInputProcessorChain.getProcessors());
-
-                        //remove the last event which will be emitted in the temporary processor above:
-                        xmlSecEventList.pollFirst();
-                        //return first event now;
-                        return xmlSecEventList.pollLast();
-                    } 
-                    break;
-                case XMLStreamConstants.END_ELEMENT:
-                    XMLSecEndElement xmlSecEndElement = xmlSecEvent.asEndElement();
-                    // Handle the signature
-                    if (signatureElementFound
-                            && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
-                            XMLSignatureInputHandler inputHandler = new XMLSignatureInputHandler();
-                            inputHandler.handle(subInputProcessorChain, getSecurityProperties(), 
-                                                xmlSecEventList, startIndexForProcessor);
-
-                        subInputProcessorChain.removeProcessor(internalBufferProcessor);
-                        subInputProcessorChain.addProcessor(
-                                new InternalReplayProcessor(getSecurityProperties()));
-
-                        //remove this processor from chain now. the next events will go directly to the other processors
-                        subInputProcessorChain.removeProcessor(this);
-                        //since we cloned the inputProcessor list we have to add the processors from
-                        //the subChain to the main chain.
-                        inputProcessorChain.getProcessors().clear();
-                        inputProcessorChain.getProcessors().addAll(subInputProcessorChain.getProcessors());
-
-                        //return first event now;
-                        return xmlSecEventList.pollLast();
+                        startIndexForProcessor = internalBufferProcessor.getXmlSecEventList().size() - 1;
                     }
-                    break;
-            }
+                }
+                break;
+            case XMLStreamConstants.END_ELEMENT:
+                XMLSecEndElement xmlSecEndElement = xmlSecEvent.asEndElement();
+                // Handle the signature
+                if (signatureElementFound
+                        && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
+                    XMLSignatureInputHandler inputHandler = new XMLSignatureInputHandler();
+
+                    final ArrayDeque<XMLSecEvent> xmlSecEventList = internalBufferProcessor.getXmlSecEventList();
+                    inputHandler.handle(inputProcessorChain, getSecurityProperties(),
+                            xmlSecEventList, startIndexForProcessor);
+
+                    inputProcessorChain.removeProcessor(internalBufferProcessor);
+
+                    //add the replay processor to the chain...
+                    InternalReplayProcessor internalReplayProcessor =
+                            new InternalReplayProcessor(getSecurityProperties(), xmlSecEventList);
+                    internalReplayProcessor.addBeforeProcessor(XMLSignatureReferenceVerifyInputProcessor.class.getName());
+                    inputProcessorChain.addProcessor(internalReplayProcessor);
+
+                    //...and let the SignatureVerificationProcessor process the buffered events (enveloped signature).
+                    InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);
+                    while (!xmlSecEventList.isEmpty()) {
+                        subInputProcessorChain.reset();
+                        subInputProcessorChain.processEvent();
+                    }
+                }
+                break;
+        }
 
-        } while (!xmlSecEvent.isEndDocument());
-        //if we reach this state we didn't find a signature nor a encryptedData Element
-        throw new XMLSecurityException("stax.unsecuredMessage");
+        return xmlSecEvent;
+    }
+
+    @Override
+    public void doFinal(InputProcessorChain inputProcessorChain) throws XMLStreamException, XMLSecurityException {
+        if (!signatureElementFound && !encryptedDataElementFound) {
+            throw new XMLSecurityException("stax.unsecuredMessage");
+        }
+        super.doFinal(inputProcessorChain);
     }
 
     /**
@@ -162,25 +163,30 @@ public class XMLSecurityInputProcessor e
      */
     public class InternalBufferProcessor extends AbstractInputProcessor {
 
+        private final ArrayDeque<XMLSecEvent> xmlSecEventList = new ArrayDeque<XMLSecEvent>();
+
         InternalBufferProcessor(XMLSecurityProperties securityProperties) {
             super(securityProperties);
             setPhase(XMLSecurityConstants.Phase.POSTPROCESSING);
             addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
         }
 
+        public ArrayDeque<XMLSecEvent> getXmlSecEventList() {
+            return xmlSecEventList;
+        }
+
         @Override
         public XMLSecEvent processNextHeaderEvent(InputProcessorChain inputProcessorChain)
                 throws XMLStreamException, XMLSecurityException {
-            XMLSecEvent xmlSecEvent = inputProcessorChain.processHeaderEvent();
-            xmlSecEventList.push(xmlSecEvent);
-            return xmlSecEvent;
+            return null;
         }
 
         @Override
         public XMLSecEvent processNextEvent(InputProcessorChain inputProcessorChain)
                 throws XMLStreamException, XMLSecurityException {
-            //should never be called because we remove this processor before
-            return null;
+            XMLSecEvent xmlSecEvent = inputProcessorChain.processEvent();
+            xmlSecEventList.push(xmlSecEvent);
+            return xmlSecEvent;
         }
     }
 
@@ -189,11 +195,11 @@ public class XMLSecurityInputProcessor e
      */
     public class InternalReplayProcessor extends AbstractInputProcessor {
 
-        public InternalReplayProcessor(XMLSecurityProperties securityProperties) {
+        private final ArrayDeque<XMLSecEvent> xmlSecEventList;
+
+        public InternalReplayProcessor(XMLSecurityProperties securityProperties, ArrayDeque<XMLSecEvent> xmlSecEventList) {
             super(securityProperties);
-            setPhase(XMLSecurityConstants.Phase.PREPROCESSING);
-            addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
-            addAfterProcessor(XMLEventReaderInputProcessor.class.getName());
+            this.xmlSecEventList = xmlSecEventList;
         }
 
         @Override

Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/output/XMLEncryptOutputProcessor.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/output/XMLEncryptOutputProcessor.java?rev=1588881&r1=1588880&r2=1588881&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/output/XMLEncryptOutputProcessor.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/output/XMLEncryptOutputProcessor.java Mon Apr 21 13:35:59 2014
@@ -303,6 +303,7 @@ public class XMLEncryptOutputProcessor e
                         createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyInfo);
                     }
                 };
+        processor.getAfterProcessors().add(XMLEncryptOutputProcessor.class.getName());
         return processor;
     }
 }

Modified: santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/signature/SignatureEncryptionTest.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/signature/SignatureEncryptionTest.java?rev=1588881&r1=1588880&r2=1588881&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/signature/SignatureEncryptionTest.java (original)
+++ santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/signature/SignatureEncryptionTest.java Mon Apr 21 13:35:59 2014
@@ -18,172 +18,284 @@
  */
 package org.apache.xml.security.test.stax.signature;
 
+import org.apache.xml.security.encryption.XMLCipher;
+import org.apache.xml.security.stax.ext.*;
+import org.apache.xml.security.stax.securityEvent.SecurityEventConstants;
+import org.apache.xml.security.test.stax.utils.StAX2DOM;
+import org.apache.xml.security.test.stax.utils.XmlReaderToWriter;
+import org.apache.xml.security.utils.XMLUtils;
+import org.junit.Assert;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESedeKeySpec;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
 import java.security.Key;
 import java.security.KeyStore;
+import java.security.PublicKey;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.DESedeKeySpec;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.stream.XMLStreamWriter;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
-import org.apache.xml.security.encryption.XMLCipher;
-import org.apache.xml.security.stax.ext.OutboundXMLSec;
-import org.apache.xml.security.stax.ext.SecurePart;
-import org.apache.xml.security.stax.ext.XMLSec;
-import org.apache.xml.security.stax.ext.XMLSecurityConstants;
-import org.apache.xml.security.stax.ext.XMLSecurityProperties;
-import org.apache.xml.security.test.stax.utils.XmlReaderToWriter;
-import org.apache.xml.security.utils.XMLUtils;
-import org.junit.Assert;
-import org.junit.Test;
-
 /**
  * A set of test-cases for Signature + Encryption.
  */
 public class SignatureEncryptionTest extends AbstractSignatureCreationTest {
-    
+
     @Test
-    public void testSignatureEncryptionCreation() throws Exception {
+    public void testSignatureEncryption() throws Exception {
         // Set up the Configuration
         XMLSecurityProperties properties = new XMLSecurityProperties();
         List<XMLSecurityConstants.Action> actions = new ArrayList<XMLSecurityConstants.Action>();
         actions.add(XMLSecurityConstants.SIGNATURE);
         actions.add(XMLSecurityConstants.ENCRYPT);
         properties.setActions(actions);
-        
+
         // Set the key up
         KeyStore keyStore = KeyStore.getInstance("jks");
         keyStore.load(
-            this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), 
-            "default".toCharArray()
+                this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
+                "default".toCharArray()
         );
         Key key = keyStore.getKey("transmitter", "default".toCharArray());
         properties.setSignatureKey(key);
-        X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
+        X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
         properties.setSignatureCerts(new X509Certificate[]{cert});
-        
+
         // Set the key up
         SecretKey encryptionKey = generateDESSecretKey();
         properties.setEncryptionKey(encryptionKey);
         properties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
-        
-        SecurePart signatureSecurePart = 
-               new SecurePart(new QName("urn:example:po", "PaymentInfo"), SecurePart.Modifier.Element);
+
+        SecurePart signatureSecurePart =
+                new SecurePart(new QName("urn:example:po", "PaymentInfo"), SecurePart.Modifier.Element);
         properties.addSignaturePart(signatureSecurePart);
-        
-        SecurePart encryptionSecurePart = 
-            new SecurePart(new QName("urn:example:po", "PurchaseOrder"), SecurePart.Modifier.Content);
+
+        SecurePart encryptionSecurePart =
+                new SecurePart(new QName("urn:example:po", "PurchaseOrder"), SecurePart.Modifier.Content);
         properties.addEncryptionPart(encryptionSecurePart);
-        
+
         OutboundXMLSec outboundXMLSec = XMLSec.getOutboundXMLSec(properties);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         XMLStreamWriter xmlStreamWriter = outboundXMLSec.processOutMessage(baos, "UTF-8");
-        
-        InputStream sourceDocument = 
+
+        InputStream sourceDocument =
                 this.getClass().getClassLoader().getResourceAsStream(
                         "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
         XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
-        
+
         XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
         xmlStreamWriter.close();
-        
+
         // System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
-        Document document = 
-            XMLUtils.createDocumentBuilder(false).parse(new ByteArrayInputStream(baos.toByteArray()));
+        Document document =
+                XMLUtils.createDocumentBuilder(false).parse(new ByteArrayInputStream(baos.toByteArray()));
 
         // Decrypt using DOM API
-        Document doc = 
-            decryptUsingDOM("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", encryptionKey, null, document);
-        
+        Document doc =
+                decryptUsingDOM("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", encryptionKey, null, document);
+
         // Check the CreditCard decrypted ok
         NodeList nodeList = doc.getElementsByTagNameNS("urn:example:po", "CreditCard");
         Assert.assertEquals(nodeList.getLength(), 1);
-        
+
         // Verify using DOM
         verifyUsingDOM(document, cert, properties.getSignatureSecureParts());
+
+        TestSecurityEventListener testSecurityEventListener =
+                verifyUsingStAX(baos.toByteArray(), encryptionKey, cert.getPublicKey());
+
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.SignedElement).size());
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.ContentEncrypted).size());
     }
-    
+
     @Test
-    public void testEnvelopedSignatureEncryptionCreation() throws Exception {
+    public void testEnvelopedSignatureEncryption() throws Exception {
         // Set up the Configuration
         XMLSecurityProperties properties = new XMLSecurityProperties();
         List<XMLSecurityConstants.Action> actions = new ArrayList<XMLSecurityConstants.Action>();
         actions.add(XMLSecurityConstants.SIGNATURE);
         actions.add(XMLSecurityConstants.ENCRYPT);
         properties.setActions(actions);
-        
+
         // Set the key up
         KeyStore keyStore = KeyStore.getInstance("jks");
         keyStore.load(
-            this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), 
-            "default".toCharArray()
+                this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
+                "default".toCharArray()
         );
         Key key = keyStore.getKey("transmitter", "default".toCharArray());
         properties.setSignatureKey(key);
-        X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
+        X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
         properties.setSignatureCerts(new X509Certificate[]{cert});
-        
+
         // Set the key up
         SecretKey encryptionKey = generateDESSecretKey();
         properties.setEncryptionKey(encryptionKey);
         properties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
-        
-        SecurePart signatureSecurePart = 
-            new SecurePart(
-                    new QName("urn:example:po", "PurchaseOrder"),
-                    SecurePart.Modifier.Content,
-                    new String[]{
-                            "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
-                            "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
-                    },
-                    "http://www.w3.org/2000/09/xmldsig#sha1"
-            );
+
+        SecurePart signatureSecurePart =
+                new SecurePart(
+                        new QName("urn:example:po", "PurchaseOrder"),
+                        SecurePart.Modifier.Content,
+                        new String[]{
+                                "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
+                                "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
+                        },
+                        "http://www.w3.org/2000/09/xmldsig#sha1"
+                );
         properties.addSignaturePart(signatureSecurePart);
-        
-        SecurePart encryptionSecurePart = 
-            new SecurePart(new QName("urn:example:po", "PurchaseOrder"), SecurePart.Modifier.Content);
+
+        SecurePart encryptionSecurePart =
+                new SecurePart(new QName("urn:example:po", "PurchaseOrder"), SecurePart.Modifier.Content);
         properties.addEncryptionPart(encryptionSecurePart);
-        
+
         OutboundXMLSec outboundXMLSec = XMLSec.getOutboundXMLSec(properties);
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         XMLStreamWriter xmlStreamWriter = outboundXMLSec.processOutMessage(baos, "UTF-8");
-        
-        InputStream sourceDocument = 
+
+        InputStream sourceDocument =
                 this.getClass().getClassLoader().getResourceAsStream(
                         "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
         XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
-        
+
         XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
         xmlStreamWriter.close();
-        
+
         // System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
-        Document document = 
-            XMLUtils.createDocumentBuilder(false).parse(new ByteArrayInputStream(baos.toByteArray()));
+        Document document =
+                XMLUtils.createDocumentBuilder(false).parse(new ByteArrayInputStream(baos.toByteArray()));
 
         // Decrypt using DOM API
-        Document doc = 
-            decryptUsingDOM("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", encryptionKey, null, document);
-        
+        Document doc =
+                decryptUsingDOM("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", encryptionKey, null, document);
+
         // Check the CreditCard decrypted ok
         NodeList nodeList = doc.getElementsByTagNameNS("urn:example:po", "CreditCard");
         Assert.assertEquals(nodeList.getLength(), 1);
-        
+
+        // Verify using DOM
+        verifyUsingDOM(document, cert, properties.getSignatureSecureParts());
+
+        TestSecurityEventListener testSecurityEventListener =
+                verifyUsingStAX(baos.toByteArray(), encryptionKey, cert.getPublicKey());
+
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.SignedElement).size());
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.ContentEncrypted).size());
+    }
+
+    @Test
+    public void testEncryptionSignature() throws Exception {
+        // Set up the Configuration
+        XMLSecurityProperties properties = new XMLSecurityProperties();
+        List<XMLSecurityConstants.Action> actions = new ArrayList<XMLSecurityConstants.Action>();
+        actions.add(XMLSecurityConstants.ENCRYPT);
+        actions.add(XMLSecurityConstants.SIGNATURE);
+        properties.setActions(actions);
+
+        // Set the key up
+        KeyStore keyStore = KeyStore.getInstance("jks");
+        keyStore.load(
+                this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
+                "default".toCharArray()
+        );
+        Key key = keyStore.getKey("transmitter", "default".toCharArray());
+        properties.setSignatureKey(key);
+        X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
+        properties.setSignatureCerts(new X509Certificate[]{cert});
+
+        // Set the key up
+        SecretKey encryptionKey = generateDESSecretKey();
+        properties.setEncryptionKey(encryptionKey);
+        properties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
+
+        SecurePart signatureSecurePart =
+                new SecurePart(
+                        new QName("urn:example:po", "PurchaseOrder"),
+                        SecurePart.Modifier.Content,
+                        new String[]{
+                                "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
+                                "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
+                        },
+                        "http://www.w3.org/2000/09/xmldsig#sha1"
+                );
+        properties.addSignaturePart(signatureSecurePart);
+
+        SecurePart encryptionSecurePart =
+                new SecurePart(new QName("urn:example:po", "PurchaseOrder"), SecurePart.Modifier.Content);
+        properties.addEncryptionPart(encryptionSecurePart);
+
+        OutboundXMLSec outboundXMLSec = XMLSec.getOutboundXMLSec(properties);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        XMLStreamWriter xmlStreamWriter = outboundXMLSec.processOutMessage(baos, "UTF-8");
+
+        InputStream sourceDocument =
+                this.getClass().getClassLoader().getResourceAsStream(
+                        "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
+
+        XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+        xmlStreamWriter.close();
+
+        // System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+        Document document =
+                XMLUtils.createDocumentBuilder(false).parse(new ByteArrayInputStream(baos.toByteArray()));
+
         // Verify using DOM
         verifyUsingDOM(document, cert, properties.getSignatureSecureParts());
+
+        // Decrypt using DOM API
+        Document doc =
+                decryptUsingDOM("http://www.w3.org/2001/04/xmlenc#tripledes-cbc", encryptionKey, null, document);
+
+        // Check the CreditCard decrypted ok
+        NodeList nodeList = doc.getElementsByTagNameNS("urn:example:po", "CreditCard");
+        Assert.assertEquals(nodeList.getLength(), 1);
+
+        TestSecurityEventListener testSecurityEventListener =
+                verifyUsingStAX(baos.toByteArray(), encryptionKey, cert.getPublicKey());
+
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.SignedElement).size());
+        Assert.assertEquals(1, testSecurityEventListener.getSecurityEvents(SecurityEventConstants.ContentEncrypted).size());
     }
-    
+
+    @Test
+    public void testUnsecuredDocument() throws Exception {
+        // Set the key up
+        KeyStore keyStore = KeyStore.getInstance("jks");
+        keyStore.load(
+                this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
+                "default".toCharArray()
+        );
+        Key key = keyStore.getKey("transmitter", "default".toCharArray());
+        X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
+
+        // Set the key up
+        SecretKey encryptionKey = generateDESSecretKey();
+
+        InputStream sourceDocument =
+                this.getClass().getClassLoader().getResourceAsStream(
+                        "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+
+        try {
+            verifyUsingStAX(sourceDocument, encryptionKey, cert.getPublicKey());
+            Assert.fail("Exception expected");
+        } catch (XMLStreamException e) {
+            Assert.assertEquals("Unsecured message. Neither a Signature nor a EncryptedData element found.",
+                    e.getCause().getMessage());
+        }
+    }
+
     /**
      * Generate a secret key
      */
@@ -193,27 +305,58 @@ public class SignatureEncryptionTest ext
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
         return keyFactory.generateSecret(keySpec);
     }
-    
+
     /**
      * Decrypt the document using DOM API and run some tests on the decrypted Document.
      */
     private Document decryptUsingDOM(
-        String algorithm, 
-        SecretKey secretKey,
-        Key wrappingKey,
-        Document document
+            String algorithm,
+            SecretKey secretKey,
+            Key wrappingKey,
+            Document document
     ) throws Exception {
         XMLCipher cipher = XMLCipher.getInstance(algorithm);
         cipher.init(XMLCipher.DECRYPT_MODE, secretKey);
         if (wrappingKey != null) {
             cipher.setKEK(wrappingKey);
         }
-        
+
         NodeList nodeList = document.getElementsByTagNameNS(
                 XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(),
                 XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart()
-            );
-        Element ee = (Element)nodeList.item(0);
+        );
+        Element ee = (Element) nodeList.item(0);
         return cipher.doFinal(document, ee);
     }
+
+    private TestSecurityEventListener verifyUsingStAX(
+            byte[] doc, Key decryptionKey, PublicKey signatureVerificationKey) throws Exception {
+        return verifyUsingStAX(new ByteArrayInputStream(doc), decryptionKey, signatureVerificationKey);
+    }
+
+    private TestSecurityEventListener verifyUsingStAX(
+            InputStream doc, Key decryptionKey, PublicKey signatureVerificationKey) throws Exception {
+
+        XMLStreamReader xmlStreamReader =
+                xmlInputFactory.createXMLStreamReader(doc);
+
+        XMLSecurityProperties properties = new XMLSecurityProperties();
+        properties.setDecryptionKey(decryptionKey);
+        properties.setSignatureVerificationKey(signatureVerificationKey);
+        InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+        TestSecurityEventListener testSecurityEventListener = new TestSecurityEventListener();
+
+        XMLStreamReader securityStreamReader =
+                inboundXMLSec.processInMessage(xmlStreamReader, null, testSecurityEventListener);
+
+        Document document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
+
+        // javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
+        // transformer.transform(new DOMSource(document), new StreamResult(System.out));
+
+        NodeList nodeList = document.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedData");
+        Assert.assertEquals(nodeList.getLength(), 0);
+
+        return testSecurityEventListener;
+    }
 }