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/07/23 15:14:15 UTC
svn commit: r1364622 - in /santuario/xml-security-java/trunk/src:
main/java/org/apache/xml/security/stax/ext/
main/java/org/apache/xml/security/stax/impl/processor/input/
main/java/org/apache/xml/security/stax/impl/securityToken/
test/java/org/apache/x...
Author: coheigea
Date: Mon Jul 23 13:14:14 2012
New Revision: 1364622
URL: http://svn.apache.org/viewvc?rev=1364622&view=rev
Log:
[SANTUARIO-329] - Added initial support for streaming decryption
Added:
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLDecryptInputProcessor.java
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java
- copied, changed from r1364565, santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSignatureInputProcessor.java
santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/encryption/DecryptionTest.java
Removed:
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSignatureInputProcessor.java
Modified:
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/InboundXMLSec.java
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityConstants.java
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityProperties.java
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractDecryptInputProcessor.java
santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java
Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/InboundXMLSec.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/InboundXMLSec.java?rev=1364622&r1=1364621&r2=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/InboundXMLSec.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/InboundXMLSec.java Mon Jul 23 13:14:14 2012
@@ -26,7 +26,7 @@ import org.apache.xml.security.stax.impl
import org.apache.xml.security.stax.impl.XMLSecurityStreamReader;
import org.apache.xml.security.stax.impl.processor.input.LogInputProcessor;
import org.apache.xml.security.stax.impl.processor.input.XMLEventReaderInputProcessor;
-import org.apache.xml.security.stax.impl.processor.input.XMLSignatureInputProcessor;
+import org.apache.xml.security.stax.impl.processor.input.XMLSecurityInputProcessor;
import org.apache.xml.security.stax.securityEvent.SecurityEvent;
import org.apache.xml.security.stax.securityEvent.SecurityEventListener;
@@ -139,12 +139,11 @@ public class InboundXMLSec {
}
}
- // TODO change
- inputProcessorChain.addProcessor(new XMLSignatureInputProcessor(securityProperties));
+ inputProcessorChain.addProcessor(new XMLSecurityInputProcessor(securityProperties));
if (log.isTraceEnabled()) {
LogInputProcessor logInputProcessor = new LogInputProcessor(securityProperties);
- logInputProcessor.addAfterProcessor(XMLSignatureInputProcessor.class.getName());
+ logInputProcessor.addAfterProcessor(XMLSecurityInputProcessor.class.getName());
inputProcessorChain.addProcessor(logInputProcessor);
}
Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityConstants.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityConstants.java?rev=1364622&r1=1364621&r2=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityConstants.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityConstants.java Mon Jul 23 13:14:14 2012
@@ -223,7 +223,7 @@ public class XMLSecurityConstants {
public static final String NS_XMLDSIG_HMACSHA1 = NS_DSIG + "hmac-sha1";
public static final String NS_XMLDSIG_RSASHA1 = NS_DSIG + "rsa-sha1";
- public static final String NS_XENC_TRIBLE_DES = NS_XMLENC + "tripledes-cbc";
+ public static final String NS_XENC_TRIPLE_DES = NS_XMLENC + "tripledes-cbc";
public static final String NS_XENC_AES128 = NS_XMLENC + "aes128-cbc";
public static final String NS_XENC_AES256 = NS_XMLENC + "aes256-cbc";
Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityProperties.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityProperties.java?rev=1364622&r1=1364621&r2=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityProperties.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/ext/XMLSecurityProperties.java Mon Jul 23 13:14:14 2012
@@ -94,6 +94,15 @@ public class XMLSecurityProperties {
private final List<SecurePart> encryptionParts = new LinkedList<SecurePart>();
private Key encryptionKey;
private Key encryptionTransportKey;
+ private Key decryptionKey;
+
+ public void setDecryptionKey(Key decryptionKey) {
+ this.decryptionKey = decryptionKey;
+ }
+
+ public Key getDecryptionKey() {
+ return decryptionKey;
+ }
public void setEncryptionTransportKey(Key encryptionTransportKey) {
this.encryptionTransportKey = encryptionTransportKey;
Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractDecryptInputProcessor.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractDecryptInputProcessor.java?rev=1364622&r1=1364621&r2=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractDecryptInputProcessor.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/AbstractDecryptInputProcessor.java Mon Jul 23 13:14:14 2012
@@ -81,6 +81,13 @@ public abstract class AbstractDecryptInp
private final ArrayDeque<XMLSecEvent> tmpXmlEventList = new ArrayDeque<XMLSecEvent>();
+ public AbstractDecryptInputProcessor(XMLSecurityProperties securityProperties) throws XMLSecurityException {
+ super(securityProperties);
+ keyInfoType = null;
+ references = null;
+ processedReferences = null;
+ }
+
public AbstractDecryptInputProcessor(KeyInfoType keyInfoType, ReferenceList referenceList,
XMLSecurityProperties securityProperties) throws XMLSecurityException {
super(securityProperties);
@@ -154,22 +161,25 @@ public abstract class AbstractDecryptInp
//check if the current start-element has the name EncryptedData and an Id attribute
if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
- ReferenceType referenceType = matchesReferenceId(xmlSecStartElement);
- if (referenceType == null) {
- //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements)
- if (!tmpXmlEventList.isEmpty()) {
- return tmpXmlEventList.pollLast();
+ ReferenceType referenceType = null;
+ if (references != null) {
+ referenceType = matchesReferenceId(xmlSecStartElement);
+ if (referenceType == null) {
+ //if the events were not for us (no matching reference-id the we have to replay the EncryptedHeader elements)
+ if (!tmpXmlEventList.isEmpty()) {
+ return tmpXmlEventList.pollLast();
+ }
+ return xmlSecEvent;
}
- return xmlSecEvent;
- }
- //duplicate id's are forbidden
- if (processedReferences.contains(referenceType)) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILED_CHECK, "duplicateId");
+ //duplicate id's are forbidden
+ if (processedReferences.contains(referenceType)) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILED_CHECK, "duplicateId");
+ }
+
+ processedReferences.add(referenceType);
}
-
tmpXmlEventList.clear();
- processedReferences.add(referenceType);
-
+
//the following logic reads the encryptedData structure and doesn't pass them further
//through the chain
InputProcessorChain subInputProcessorChain = inputProcessorChain.createSubChain(this);
@@ -199,7 +209,7 @@ public abstract class AbstractDecryptInp
parentXMLSecStartElement = parentXMLSecStartElement.getParentXMLSecStartElement();
}
AbstractDecryptedEventReaderInputProcessor decryptedEventReaderInputProcessor =
- newDecryptedEventReaderInputProccessor(
+ newDecryptedEventReaderInputProcessor(
encryptedHeader, parentXMLSecStartElement, encryptedDataType, securityToken,
inputProcessorChain.getSecurityContext()
);
@@ -235,29 +245,31 @@ public abstract class AbstractDecryptInp
InputStream decryptInputStream = decryptionThread.getPipedInputStream();
- TransformsType transformsType =
- XMLSecurityUtils.getQNameType(referenceType.getAny(), XMLSecurityConstants.TAG_dsig_Transforms);
- if (transformsType != null) {
- List<TransformType> transformTypes = transformsType.getTransform();
- if (transformTypes.size() > 1) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.INVALID_SECURITY);
- }
- TransformType transformType = transformTypes.get(0);
- @SuppressWarnings("unchecked")
- Class<InputStream> transformerClass =
- (Class<InputStream>) TransformerAlgorithmMapper.getTransformerClass(
- transformType.getAlgorithm(), XMLSecurityConstants.DIRECTION.IN);
- try {
- Constructor<InputStream> constructor = transformerClass.getConstructor(InputStream.class);
- decryptInputStream = constructor.newInstance(decryptInputStream);
- } catch (InvocationTargetException e) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
- } catch (NoSuchMethodException e) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
- } catch (InstantiationException e) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
- } catch (IllegalAccessException e) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
+ if (referenceType != null) {
+ TransformsType transformsType =
+ XMLSecurityUtils.getQNameType(referenceType.getAny(), XMLSecurityConstants.TAG_dsig_Transforms);
+ if (transformsType != null) {
+ List<TransformType> transformTypes = transformsType.getTransform();
+ if (transformTypes.size() > 1) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.INVALID_SECURITY);
+ }
+ TransformType transformType = transformTypes.get(0);
+ @SuppressWarnings("unchecked")
+ Class<InputStream> transformerClass =
+ (Class<InputStream>) TransformerAlgorithmMapper.getTransformerClass(
+ transformType.getAlgorithm(), XMLSecurityConstants.DIRECTION.IN);
+ try {
+ Constructor<InputStream> constructor = transformerClass.getConstructor(InputStream.class);
+ decryptInputStream = constructor.newInstance(decryptInputStream);
+ } catch (InvocationTargetException e) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
+ } catch (NoSuchMethodException e) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
+ } catch (InstantiationException e) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
+ } catch (IllegalAccessException e) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILURE, e);
+ }
}
}
@@ -465,7 +477,7 @@ public abstract class AbstractDecryptInp
return xmlSecEvent;
}
- protected abstract AbstractDecryptedEventReaderInputProcessor newDecryptedEventReaderInputProccessor(
+ protected abstract AbstractDecryptedEventReaderInputProcessor newDecryptedEventReaderInputProcessor(
boolean encryptedHeader, XMLSecStartElement xmlSecStartElement, EncryptedDataType currentEncryptedDataType,
SecurityToken securityToken, SecurityContext securityContext) throws XMLSecurityException;
@@ -488,11 +500,13 @@ public abstract class AbstractDecryptInp
@Override
public void doFinal(InputProcessorChain inputProcessorChain) throws XMLStreamException, XMLSecurityException {
//here we check if all references where processed.
- Iterator<Map.Entry<String, ReferenceType>> refEntryIterator = this.references.entrySet().iterator();
- while (refEntryIterator.hasNext()) {
- Map.Entry<String, ReferenceType> referenceTypeEntry = refEntryIterator.next();
- if (!processedReferences.contains(referenceTypeEntry.getValue())) {
- throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILED_CHECK, "unprocessedEncryptionReferences");
+ if (references != null) {
+ Iterator<Map.Entry<String, ReferenceType>> refEntryIterator = this.references.entrySet().iterator();
+ while (refEntryIterator.hasNext()) {
+ Map.Entry<String, ReferenceType> referenceTypeEntry = refEntryIterator.next();
+ if (!processedReferences.contains(referenceTypeEntry.getValue())) {
+ throw new XMLSecurityException(XMLSecurityException.ErrorCode.FAILED_CHECK, "unprocessedEncryptionReferences");
+ }
}
}
inputProcessorChain.doFinal();
Added: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLDecryptInputProcessor.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLDecryptInputProcessor.java?rev=1364622&view=auto
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLDecryptInputProcessor.java (added)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLDecryptInputProcessor.java Mon Jul 23 13:14:14 2012
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.stax.impl.processor.input;
+
+import org.apache.xml.security.binding.xmldsig.KeyInfoType;
+import org.apache.xml.security.binding.xmlenc.EncryptedDataType;
+import org.apache.xml.security.binding.xmlenc.ReferenceList;
+import org.apache.xml.security.stax.ext.InputProcessorChain;
+import org.apache.xml.security.stax.ext.SecurePart;
+import org.apache.xml.security.stax.ext.SecurityContext;
+import org.apache.xml.security.stax.ext.SecurityToken;
+import org.apache.xml.security.stax.ext.XMLSecurityException;
+import org.apache.xml.security.stax.ext.XMLSecurityProperties;
+import org.apache.xml.security.stax.ext.stax.XMLSecStartElement;
+
+
+/**
+ * Processor for decryption of EncryptedData XML structures
+ *
+ * @author $Author: giger $
+ * @version $Revision: 1228829 $ $Date: 2012-01-08 11:44:13 +0000 (Sun, 08 Jan 2012) $
+ */
+public class XMLDecryptInputProcessor extends AbstractDecryptInputProcessor {
+
+ public XMLDecryptInputProcessor(XMLSecurityProperties securityProperties) throws XMLSecurityException {
+ super(securityProperties);
+ }
+
+ public XMLDecryptInputProcessor(
+ KeyInfoType keyInfoType, ReferenceList referenceList,
+ XMLSecurityProperties securityProperties
+ ) throws XMLSecurityException {
+ super(keyInfoType, referenceList, securityProperties);
+ }
+
+ @Override
+ protected AbstractDecryptedEventReaderInputProcessor newDecryptedEventReaderInputProcessor(
+ boolean encryptedHeader, XMLSecStartElement xmlSecStartElement, EncryptedDataType currentEncryptedDataType,
+ SecurityToken securityToken, SecurityContext securityContext) throws XMLSecurityException {
+ return new DecryptedEventReaderInputProcessor(getSecurityProperties(),
+ SecurePart.Modifier.getModifier(currentEncryptedDataType.getType()),
+ encryptedHeader, xmlSecStartElement, this, securityToken);
+ }
+
+ @Override
+ protected void handleSecurityToken(
+ SecurityToken securityToken, SecurityContext securityContext, EncryptedDataType encryptedDataType) throws XMLSecurityException {
+ /*
+ * securityToken.addTokenUsage(SecurityToken.TokenUsage.Encryption);
+ TokenSecurityEvent tokenSecurityEvent = WSSUtils.createTokenSecurityEvent(securityToken);
+ securityContext.registerSecurityEvent(tokenSecurityEvent);
+ */
+ }
+
+ @Override
+ protected void handleEncryptedContent(InputProcessorChain inputProcessorChain,
+ XMLSecStartElement parentXMLSecStartElement,
+ SecurityToken securityToken) throws XMLSecurityException {
+ // TODO
+ /*
+ * final DocumentContext documentContext = inputProcessorChain.getDocumentContext();
+ List<QName> elementPath = parentStartXMLEvent.getElementPath();
+ if (elementPath.size() == 2 && WSSUtils.isInSOAPBody(elementPath)) {
+ //soap:body content encryption counts as EncryptedPart
+ EncryptedPartSecurityEvent encryptedPartSecurityEvent =
+ new EncryptedPartSecurityEvent(securityToken, true, documentContext.getProtectionOrder());
+ encryptedPartSecurityEvent.setElementPath(elementPath);
+ encryptedPartSecurityEvent.setXmlSecEvent(parentStartXMLEvent);
+ ((WSSecurityContext) inputProcessorChain.getSecurityContext()).registerSecurityEvent(encryptedPartSecurityEvent);
+ } else {
+ ContentEncryptedElementSecurityEvent contentEncryptedElementSecurityEvent =
+ new ContentEncryptedElementSecurityEvent(securityToken, true, documentContext.getProtectionOrder());
+ contentEncryptedElementSecurityEvent.setElementPath(elementPath);
+ contentEncryptedElementSecurityEvent.setXmlSecEvent(parentStartXMLEvent);
+ ((WSSecurityContext) inputProcessorChain.getSecurityContext()).registerSecurityEvent(contentEncryptedElementSecurityEvent);
+ }
+ */
+ }
+
+ /**
+ * The DecryptedEventReaderInputProcessor reads the decrypted stream with a StAX reader and
+ * forwards the generated XMLEvents
+ */
+ public class DecryptedEventReaderInputProcessor extends AbstractDecryptedEventReaderInputProcessor {
+
+ public DecryptedEventReaderInputProcessor(
+ XMLSecurityProperties securityProperties, SecurePart.Modifier encryptionModifier,
+ boolean encryptedHeader, XMLSecStartElement xmlSecStartElement,
+ XMLDecryptInputProcessor decryptInputProcessor,
+ SecurityToken securityToken
+ ) {
+ super(securityProperties, encryptionModifier, encryptedHeader, xmlSecStartElement, decryptInputProcessor, securityToken);
+ }
+
+ @Override
+ protected void handleEncryptedElement(InputProcessorChain inputProcessorChain, XMLSecStartElement xmlSecStartElement,
+ SecurityToken securityToken) throws XMLSecurityException {
+ //fire a SecurityEvent:
+ /* TODO
+ * EncryptedElementSecurityEvent encryptedElementSecurityEvent =
+ new EncryptedElementSecurityEvent(securityToken, true, documentContext.getProtectionOrder());
+ encryptedElementSecurityEvent.setElementPath(elementPath);
+ encryptedElementSecurityEvent.setXmlSecEvent(xmlSecStartElement);
+ ((WSSecurityContext) inputProcessorChain.getSecurityContext()).registerSecurityEvent(encryptedElementSecurityEvent);
+ */
+ }
+
+ }
+}
Copied: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java (from r1364565, santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSignatureInputProcessor.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?p2=santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java&p1=santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSignatureInputProcessor.java&r1=1364565&r2=1364622&rev=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSignatureInputProcessor.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/processor/input/XMLSecurityInputProcessor.java Mon Jul 23 13:14:14 2012
@@ -35,20 +35,20 @@ import org.apache.xml.security.stax.ext.
import org.apache.xml.security.stax.ext.stax.XMLSecStartElement;
/**
- * Processor for XML Signature.
+ * Processor for XML Security.
*
* @author $Author: coheigea $
* @version $Revision: 1354898 $ $Date: 2012-06-28 11:19:02 +0100 (Thu, 28 Jun 2012) $
*/
-public class XMLSignatureInputProcessor extends AbstractInputProcessor {
+public class XMLSecurityInputProcessor extends AbstractInputProcessor {
- protected static final transient Log logger = LogFactory.getLog(XMLSignatureInputProcessor.class);
+ protected static final transient Log logger = LogFactory.getLog(XMLSecurityInputProcessor.class);
private final ArrayDeque<XMLSecEvent> xmlSecEventList = new ArrayDeque<XMLSecEvent>();
private int eventCount = 0;
private int startIndexForProcessor = 0;
- public XMLSignatureInputProcessor(XMLSecurityProperties securityProperties) {
+ public XMLSecurityInputProcessor(XMLSecurityProperties securityProperties) {
super(securityProperties);
setPhase(XMLSecurityConstants.Phase.POSTPROCESSING);
}
@@ -69,7 +69,8 @@ public class XMLSignatureInputProcessor
= new InternalBufferProcessor(getSecurityProperties());
subInputProcessorChain.addProcessor(internalBufferProcessor);
- boolean elementFound = false;
+ boolean signatureElementFound = false;
+ boolean encryptionElementFound = false;
XMLSecEvent xmlSecEvent;
do {
@@ -82,18 +83,30 @@ public class XMLSignatureInputProcessor
XMLSecStartElement xmlSecStartElement = xmlSecEvent.asStartElement();
if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
- elementFound = true;
+ signatureElementFound = true;
startIndexForProcessor = eventCount - 1;
- }
+ } else if (xmlSecStartElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
+ encryptionElementFound = true;
+ startIndexForProcessor = eventCount - 1;
+ }
break;
case XMLStreamConstants.END_ELEMENT:
XMLSecEndElement xmlSecEndElement = xmlSecEvent.asEndElement();
- if (elementFound
- && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature)) {
+ if ((signatureElementFound
+ && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature))
+ || (encryptionElementFound
+ && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData))) {
// Handle the signature
- XMLSignatureInputHandler inputHandler = new XMLSignatureInputHandler();
- inputHandler.handle(subInputProcessorChain, getSecurityProperties(),
- xmlSecEventList, startIndexForProcessor);
+ if ((signatureElementFound
+ && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_dsig_Signature))) {
+ XMLSignatureInputHandler inputHandler = new XMLSignatureInputHandler();
+ inputHandler.handle(subInputProcessorChain, getSecurityProperties(),
+ xmlSecEventList, startIndexForProcessor);
+ } else if (encryptionElementFound
+ && xmlSecEndElement.getName().equals(XMLSecurityConstants.TAG_xenc_EncryptedData)) {
+ XMLDecryptInputProcessor inputProcessor = new XMLDecryptInputProcessor( getSecurityProperties());
+ subInputProcessorChain.addProcessor(inputProcessor);
+ }
subInputProcessorChain.removeProcessor(internalBufferProcessor);
subInputProcessorChain.addProcessor(
@@ -125,7 +138,7 @@ public class XMLSignatureInputProcessor
InternalBufferProcessor(XMLSecurityProperties securityProperties) {
super(securityProperties);
setPhase(XMLSecurityConstants.Phase.POSTPROCESSING);
- addBeforeProcessor(XMLSignatureInputProcessor.class.getName());
+ addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
}
@Override
@@ -152,7 +165,7 @@ public class XMLSignatureInputProcessor
public InternalReplayProcessor(XMLSecurityProperties securityProperties) {
super(securityProperties);
setPhase(XMLSecurityConstants.Phase.PREPROCESSING);
- addBeforeProcessor(XMLSignatureInputProcessor.class.getName());
+ addBeforeProcessor(XMLSecurityInputProcessor.class.getName());
addAfterProcessor(XMLEventReaderInputProcessor.class.getName());
}
Modified: santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java?rev=1364622&r1=1364621&r2=1364622&view=diff
==============================================================================
--- santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java (original)
+++ santuario/xml-security-java/trunk/src/main/java/org/apache/xml/security/stax/impl/securityToken/SecurityTokenFactoryImpl.java Mon Jul 23 13:14:14 2012
@@ -95,12 +95,20 @@ public class SecurityTokenFactoryImpl ex
}
// Use a default key if it exists
- if (securityProperties.getSignatureVerificationKey() != null) {
+ if (keyInfoUsage == SecurityToken.KeyInfoUsage.SIGNATURE_VERIFICATION
+ && securityProperties.getSignatureVerificationKey() != null) {
DefaultSecurityToken token =
new DefaultSecurityToken(securityContext, securityProperties.getCallbackHandler(), "",
XMLSecurityConstants.XMLKeyIdentifierType.NO_KEY_INFO);
token.setKey(securityProperties.getSignatureVerificationKey());
return token;
+ } else if (keyInfoUsage == SecurityToken.KeyInfoUsage.DECRYPTION
+ && securityProperties.getDecryptionKey() != null) {
+ DefaultSecurityToken token =
+ new DefaultSecurityToken(securityContext, securityProperties.getCallbackHandler(), "",
+ XMLSecurityConstants.XMLKeyIdentifierType.NO_KEY_INFO);
+ token.setKey(securityProperties.getDecryptionKey());
+ return token;
}
throw new XMLSecurityException(XMLSecurityException.ErrorCode.INVALID_SECURITY, "noKeyinfo");
Added: santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/encryption/DecryptionTest.java
URL: http://svn.apache.org/viewvc/santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/encryption/DecryptionTest.java?rev=1364622&view=auto
==============================================================================
--- santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/encryption/DecryptionTest.java (added)
+++ santuario/xml-security-java/trunk/src/test/java/org/apache/xml/security/test/stax/encryption/DecryptionTest.java Mon Jul 23 13:14:14 2012
@@ -0,0 +1,493 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.xml.security.test.stax.encryption;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESedeKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+
+import org.apache.xml.security.encryption.EncryptedData;
+import org.apache.xml.security.encryption.EncryptedKey;
+import org.apache.xml.security.encryption.XMLCipher;
+import org.apache.xml.security.keys.KeyInfo;
+import org.apache.xml.security.stax.ext.InboundXMLSec;
+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.dom.DSNamespaceContext;
+import org.apache.xml.security.test.stax.signature.TestSecurityEventListener;
+import org.apache.xml.security.test.stax.utils.StAX2DOM;
+import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
+import org.apache.xml.security.utils.XMLUtils;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+/**
+ * A set of test-cases for Decryption.
+ *
+ * @author $Author: coheigea $
+ * @version $Revision: 1236690 $ $Date: 2012-01-27 14:07:10 +0000 (Fri, 27 Jan 2012) $
+ */
+public class DecryptionTest extends org.junit.Assert {
+
+ private XMLInputFactory xmlInputFactory;
+ private DocumentBuilderFactory documentBuilderFactory;
+ private TransformerFactory transformerFactory = TransformerFactory.newInstance();
+
+ @Before
+ public void setUp() throws Exception {
+ org.apache.xml.security.Init.init();
+
+ xmlInputFactory = XMLInputFactory.newInstance();
+ xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
+
+ documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ documentBuilderFactory.setNamespaceAware(true);
+ documentBuilderFactory.setIgnoringComments(false);
+ documentBuilderFactory.setCoalescing(false);
+ documentBuilderFactory.setIgnoringElementContentWhitespace(false);
+ }
+
+ @Test
+ public void testDecryptElementValidation() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream(
+ "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Set up the Key
+ SecretKey secretKey = generateSecretKey();
+
+ // Encrypt using DOM
+ List<String> localNames = new ArrayList<String>();
+ localNames.add("PaymentInfo");
+ encryptUsingDOM(
+ "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", secretKey, null, null, document,
+ localNames, false
+ );
+
+ // Check the CreditCard encrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ // XMLUtils.outputDOM(document, System.out);
+
+ // Convert Document to a Stream Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLStreamReader xmlStreamReader =
+ xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Decrypt
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.setDecryptionKey(secretKey);
+ InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+ TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
+ XMLStreamReader securityStreamReader =
+ inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
+
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), securityStreamReader);
+
+ // Check the CreditCard decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // TODO Check the SecurityEvents
+ }
+
+
+ @Test
+ public void testDecryptContentValidation() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream(
+ "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Set up the Key
+ SecretKey secretKey = generateSecretKey();
+
+ // Encrypt using DOM
+ List<String> localNames = new ArrayList<String>();
+ localNames.add("PaymentInfo");
+ encryptUsingDOM(
+ "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", secretKey, null, null, document,
+ localNames, true
+ );
+
+ // Check the CreditCard encrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ // XMLUtils.outputDOM(document, System.out);
+
+ // Convert Document to a Stream Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLStreamReader xmlStreamReader =
+ xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Decrypt
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.setDecryptionKey(secretKey);
+ InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+ TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
+ XMLStreamReader securityStreamReader =
+ inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
+
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), securityStreamReader);
+
+ // Check the CreditCard decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // TODO Check the SecurityEvents
+ }
+
+ @Test
+ public void testStrongDecryption() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream(
+ "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Set up the Key
+ KeyGenerator keygen = KeyGenerator.getInstance("AES");
+ keygen.init(256);
+ SecretKey secretKey = keygen.generateKey();
+
+ // Encrypt using DOM
+ List<String> localNames = new ArrayList<String>();
+ localNames.add("PaymentInfo");
+ encryptUsingDOM(
+ "http://www.w3.org/2001/04/xmlenc#aes256-cbc", secretKey, null, null, document,
+ localNames, false
+ );
+
+ // Check the CreditCard encrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ // XMLUtils.outputDOM(document, System.out);
+
+ // Convert Document to a Stream Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLStreamReader xmlStreamReader =
+ xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Decrypt
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.setDecryptionKey(secretKey);
+ InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+ TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
+ XMLStreamReader securityStreamReader =
+ inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
+
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), securityStreamReader);
+
+ // Check the CreditCard decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // TODO Check the SecurityEvents
+ }
+
+ @Test
+ public void testDecryptMultipleElements() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream(
+ "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Set up the Key
+ SecretKey secretKey = generateSecretKey();
+
+ // Encrypt using DOM
+ List<String> localNames = new ArrayList<String>();
+ localNames.add("PaymentInfo");
+ localNames.add("ShippingAddress");
+ encryptUsingDOM(
+ "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", secretKey, null, null, document,
+ localNames, false
+ );
+
+ // Check the CreditCard encrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ // XMLUtils.outputDOM(document, System.out);
+
+ // Convert Document to a Stream Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLStreamReader xmlStreamReader =
+ xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Decrypt
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.setDecryptionKey(secretKey);
+ InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+ TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
+ XMLStreamReader securityStreamReader =
+ inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
+
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), securityStreamReader);
+
+ // Check the CreditCard decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // Check the ShippingAddress decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "ShippingAddress");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // TODO Check the SecurityEvents
+ }
+
+ // TODO
+ @Test
+ @org.junit.Ignore
+ public void testAES128ElementAES192KWCipherUsingKEKInbound() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream(
+ "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Set up the Key
+ byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
+ SecretKey kek = new SecretKeySpec(bits192, "AES");
+
+ // Generate a traffic key
+ KeyGenerator keygen = KeyGenerator.getInstance("AES");
+ keygen.init(128);
+ SecretKey secretKey = keygen.generateKey();
+
+ // Encrypt using DOM
+ List<String> localNames = new ArrayList<String>();
+ localNames.add("PaymentInfo");
+ encryptUsingDOM(
+ "http://www.w3.org/2001/04/xmlenc#aes128-cbc", secretKey,
+ "http://www.w3.org/2001/04/xmlenc#kw-aes192", kek, document, localNames, true
+ );
+
+ // Check the CreditCard encrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 0);
+
+ XMLUtils.outputDOM(document, System.out);
+
+ // Convert Document to a Stream Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLStreamReader xmlStreamReader =
+ xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Decrypt
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.setDecryptionKey(kek);
+ InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
+ TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
+ XMLStreamReader securityStreamReader =
+ inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
+
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), securityStreamReader);
+
+ // Check the CreditCard decrypted ok
+ nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ // TODO Check the SecurityEvents
+ }
+
+ /*
+ @Test
+ /**
+ * Test encryption using a generated AES 128 bit key that is
+ * encrypted using a AES 192 bit key. Then reverse using the KEK
+ @Test
+ public void testAES128ElementAES192KWCipherUsingKEKOutbound() throws Exception {
+ // Read in plaintext document
+ InputStream sourceDocument =
+ this.getClass().getClassLoader().getResourceAsStream("testdata/plaintext.xml");
+ DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
+ Document document = builder.parse(sourceDocument);
+
+ // Generate the SecretKey
+ // Set up a Key Encryption Key
+ byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
+ SecretKey kek = new SecretKeySpec(bits192, "AES");
+
+ // Generate a traffic key
+ KeyGenerator keygen = KeyGenerator.getInstance("AES");
+ keygen.init(128);
+ SecretKey secretKey = keygen.generateKey();
+
+ // Encrypt using Apache Santuario
+ encryptUsingSantuario(
+ "http://www.w3.org/2001/04/xmlenc#aes128-cbc", secretKey,
+ "http://www.w3.org/2001/04/xmlenc#kw-aes192", kek, document, false
+ );
+
+ XMLUtils.outputDOM(document, System.out);
+
+ // Set up key
+ SecurityContextImpl securityContextImpl = new SecurityContextImpl();
+ EncryptionSecurityToken securityToken = new EncryptionSecurityToken(secretKey);
+ securityContextImpl.put(XMLSecurityConstants.XMLINPUTFACTORY, xmlInputFactory);
+
+ // Set up the Configuration
+ XMLSecurityProperties properties = new XMLSecurityProperties();
+ properties.loadDecryptionKeystore(
+ this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray()
+ );
+ final DocumentContextImpl documentContext = new DocumentContextImpl();
+ documentContext.setEncoding("UTF-8");
+
+ // Convert Document to an Event Reader
+ javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ transformer.transform(new DOMSource(document), new StreamResult(baos));
+ final XMLEventReader xmlEventReader =
+ xmlInputFactory.createXMLEventReader(new ByteArrayInputStream(baos.toByteArray()));
+
+ // Set up the processor chain
+ InputProcessorChainImpl processorChain =
+ new InputProcessorChainImpl(securityContextImpl, documentContext);
+ processorChain.addProcessor(new XMLEventReaderInputProcessor(properties, xmlEventReader));
+ XMLDecryptInputProcessor decProcessor = new XMLDecryptInputProcessor(null, properties);
+ decProcessor.setSecurityToken(securityToken);
+ processorChain.addProcessor(decProcessor);
+
+ XMLStreamReader newStreamReader = new XMLSecurityStreamReader(processorChain, properties);
+ document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), newStreamReader);
+
+ XMLUtils.outputDOM(document, System.out);
+
+ // Check the CreditCard decrypted ok
+ NodeList nodeList = document.getElementsByTagNameNS("urn:example:po", "CreditCard");
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ */
+
+ /**
+ * Generate a secret key
+ */
+ private SecretKey generateSecretKey() throws Exception {
+ byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
+ DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
+ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
+ return keyFactory.generateSecret(keySpec);
+ }
+
+ /**
+ * Encrypt the document using DOM APIs and run some tests on the encrypted Document.
+ */
+ private void encryptUsingDOM(
+ String algorithm,
+ SecretKey secretKey,
+ String keyTransportAlgorithm,
+ SecretKey wrappingKey,
+ Document document,
+ List<String> localNames,
+ boolean content
+ ) throws Exception {
+ XMLCipher cipher = XMLCipher.getInstance(algorithm);
+ cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
+
+ if (wrappingKey != null) {
+ XMLCipher newCipher = XMLCipher.getInstance(keyTransportAlgorithm);
+ newCipher.init(XMLCipher.WRAP_MODE, wrappingKey);
+ EncryptedKey encryptedKey = newCipher.encryptKey(document, wrappingKey);
+
+ EncryptedData builder = cipher.getEncryptedData();
+
+ KeyInfo builderKeyInfo = builder.getKeyInfo();
+ if (builderKeyInfo == null) {
+ builderKeyInfo = new KeyInfo(document);
+ builderKeyInfo.getElement().setAttributeNS(
+ "http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#"
+ );
+ builder.setKeyInfo(builderKeyInfo);
+ }
+
+ builderKeyInfo.add(encryptedKey);
+ }
+
+ XPathFactory xpf = XPathFactory.newInstance();
+ XPath xpath = xpf.newXPath();
+ xpath.setNamespaceContext(new DSNamespaceContext());
+
+ for (String localName : localNames) {
+ String expression = "//*[local-name()='" + localName + "']";
+ Element elementToEncrypt =
+ (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
+ Assert.assertNotNull(elementToEncrypt);
+ String id = UUID.randomUUID().toString();
+ elementToEncrypt.setAttributeNS(null, "Id", id);
+ elementToEncrypt.setIdAttributeNS(null, "Id", true);
+
+ document = cipher.doFinal(document, elementToEncrypt, content);
+ }
+
+ NodeList nodeList = document.getElementsByTagNameNS(
+ XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(),
+ XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart()
+ );
+ Assert.assertTrue(nodeList.getLength() > 0);
+ }
+
+}