You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by gi...@apache.org on 2011/09/18 15:51:36 UTC
svn commit: r1172285 [34/48] - in /webservices/wss4j/branches/swssf: ./
cxf-integration/ cxf-integration/src/ cxf-integration/src/main/
cxf-integration/src/main/java/ cxf-integration/src/main/java/org/
cxf-integration/src/main/java/org/swssf/ cxf-integ...
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315ExclusiveTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315ExclusiveTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315ExclusiveTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315ExclusiveTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,264 @@
+/**
+ * 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.swssf.test;
+
+import org.swssf.ext.Constants;
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer20010315_ExclOmitCommentsTransformer;
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer20010315_ExclWithCommentsTransformer;
+import org.swssf.test.utils.XMLEventNSAllocator;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.events.XMLEvent;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.net.URL;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class Canonicalizer20010315ExclusiveTest {
+
+ private XMLInputFactory xmlInputFactory;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ this.xmlInputFactory = XMLInputFactory.newFactory();
+ this.xmlInputFactory.setEventAllocator(new XMLEventNSAllocator());
+ }
+
+ @Test
+ public void test221excl() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer(null, baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/inExcl/example2_2_1.xml")
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ }
+ while (xmlEventReader.hasNext()) {
+
+ c.transform(xmlEvent);
+
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
+ boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+ if (!equals) {
+ System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+ System.out.println("");
+ System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+ }
+
+ assertTrue(equals);
+ }
+
+ @Test
+ public void test222excl() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer(null, baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/inExcl/example2_2_2.xml")
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ }
+ while (xmlEventReader.hasNext()) {
+
+ c.transform(xmlEvent);
+
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/inExcl/example2_2_c14nized_exclusive.xml"));
+ boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+ if (!equals) {
+ System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+ System.out.println("");
+ System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+ }
+
+ assertTrue(equals);
+ }
+
+ @Test
+ public void testComplexDocexcl() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_ExclWithCommentsTransformer c = new Canonicalizer20010315_ExclWithCommentsTransformer(null, baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml")
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(Constants.TAG_soap11_Body)) {
+ break;
+ }
+ }
+ while (xmlEventReader.hasNext()) {
+
+ c.transform(xmlEvent);
+
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(Constants.TAG_soap11_Body)) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/inExcl/plain-soap-c14nized.xml"));
+ boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+ if (!equals) {
+ System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+ System.out.println("");
+ System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+ }
+/*
+ for (int i = 0; i < reference.length; i++) {
+ if (reference[i] != baos.toByteArray()[i]) {
+ System.out.println("Expected diff: " + new String(reference, i - 10, 20));
+ System.out.println("Got diff: " + new String(baos.toByteArray(), i - 10, 20));
+ return;
+ }
+ }
+*/
+ assertTrue(equals);
+ }
+
+ @Test
+ public void testNodeSet() throws Exception {
+
+ final String XML =
+ "<env:Envelope"
+ + " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
+ + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ + " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ + " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
+ + "<env:Body wsu:Id=\"body\">"
+ + "<ns0:Ping xsi:type=\"ns0:ping\">"
+ + "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ + "</ns0:Ping>"
+ + "</env:Body>"
+ + "</env:Envelope>";
+
+ final String c14nXML =
+ "<env:Body"
+ + " xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ + " xmlns:ns0=\"http://xmlsoap.org/Ping\""
+ + " xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\""
+ + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ + " wsu:Id=\"body\">"
+ + "<ns0:Ping xsi:type=\"ns0:ping\">"
+ + "<ns0:text xsi:type=\"xsd:string\">hello</ns0:text>"
+ + "</ns0:Ping>"
+ + "</env:Body>";
+
+/* Set nodeSet = new HashSet();
+ XMLUtils.getSet
+ (doc.getDocumentElement().getFirstChild(), nodeSet, null, false);
+ XMLSignatureInput input = new XMLSignatureInput(nodeSet);
+ byte[] bytes = c14n.engineCanonicalize(input, "env ns0 xsi wsu");
+
+*/
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_ExclOmitCommentsTransformer c = new Canonicalizer20010315_ExclOmitCommentsTransformer("env ns0 xsi wsu", baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ new StringReader(XML)
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"))) {
+ break;
+ }
+ }
+
+ while (xmlEventReader.hasNext()) {
+ c.transform(xmlEvent);
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"))) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ assertEquals(new String(baos.toByteArray()), c14nXML);
+ }
+ /*
+ private String getAbsolutePath(String path)
+ {
+ String basedir = System.getProperty("basedir");
+ if(basedir != null && !"".equals(basedir)) {
+ path = basedir + "/" + path;
+ }
+ return path;
+ }
+ */
+
+ public static byte[] getBytesFromResource(URL resource) throws IOException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ InputStream inputStream = resource.openStream();
+ try {
+ byte buf[] = new byte[1024];
+ int len;
+ while ((len = inputStream.read(buf)) > 0) {
+ baos.write(buf, 0, len);
+ }
+
+ return baos.toByteArray();
+ } finally {
+ inputStream.close();
+ }
+ }
+}
\ No newline at end of file
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315ExclusiveTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315Test.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315Test.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315Test.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315Test.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,706 @@
+/**
+ * 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.swssf.test;
+
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer20010315_OmitCommentsTransformer;
+import org.swssf.impl.transformer.canonicalizer.Canonicalizer20010315_WithCommentsTransformer;
+import org.swssf.impl.transformer.canonicalizer.CanonicalizerBase;
+import org.swssf.test.utils.XMLEventNSAllocator;
+import org.testng.annotations.Test;
+
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLResolver;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.XMLEvent;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+import static org.testng.Assert.*;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class Canonicalizer20010315Test {
+
+ private XMLInputFactory xmlInputFactory;
+
+ public Canonicalizer20010315Test() throws Exception {
+ this.xmlInputFactory = XMLInputFactory.newFactory();
+ this.xmlInputFactory.setEventAllocator(new XMLEventNSAllocator());
+ XMLResolver xmlResolver = new XMLResolver() {
+ public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException {
+ return this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/in/" + systemID);
+ }
+ };
+ this.xmlInputFactory.setXMLResolver(xmlResolver);
+ }
+
+ @Test
+ public void test221() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_WithCommentsTransformer c = new Canonicalizer20010315_WithCommentsTransformer(null, baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/inExcl/example2_2_1.xml")
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ }
+ while (xmlEventReader.hasNext()) {
+
+ c.transform(xmlEvent);
+
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/inExcl/example2_2_1_c14nized.xml"));
+ boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+ if (!equals) {
+ System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+ System.out.println("");
+ System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+ }
+
+ assertTrue(equals);
+ }
+
+ @Test
+ public void test222() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Canonicalizer20010315_WithCommentsTransformer c = new Canonicalizer20010315_WithCommentsTransformer(null, baos);
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(
+ this.getClass().getClassLoader().getResourceAsStream("testdata/c14n/inExcl/example2_2_2.xml")
+ );
+
+ XMLEvent xmlEvent = null;
+ while (xmlEventReader.hasNext()) {
+ xmlEvent = xmlEventReader.nextEvent();
+ if (xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ }
+ while (xmlEventReader.hasNext()) {
+
+ c.transform(xmlEvent);
+
+ if (xmlEvent.isEndElement() && xmlEvent.asEndElement().getName().equals(new QName("http://example.net", "elem2"))) {
+ break;
+ }
+ xmlEvent = xmlEventReader.nextEvent();
+ }
+
+ byte[] reference = getBytesFromResource(this.getClass().getClassLoader().getResource("testdata/c14n/inExcl/example2_2_2_c14nized.xml"));
+ boolean equals = java.security.MessageDigest.isEqual(reference, baos.toByteArray());
+
+ if (!equals) {
+ System.out.println("Expected:\n" + new String(reference, "UTF-8"));
+ System.out.println("");
+ System.out.println("Got:\n" + new String(baos.toByteArray(), "UTF-8"));
+ }
+
+ assertTrue(equals);
+ }
+
+ /**
+ * 3.1 PIs, Comments, and Outside of Document Element
+ */
+ @Test
+ public void test31withCommentsSubtree() throws Exception {
+
+ String descri =
+ "3.1: PIs, Comments, and Outside of Document Element. (commented)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_c14n-comments.xml");
+
+ c14nAndCompare(fileIn, fileRef, false);
+ }
+
+ /**
+ * 3.1 PIs, Comments, and Outside of Document Element
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-OutsideDoc">the example from the spec</A>
+ */
+ @Test
+ public void test31subtree() throws Exception {
+
+ String descri =
+ "3.1: PIs, Comments, and Outside of Document Element. (uncommented)";
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/31_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.2 Whitespace in Document Content
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-WhitespaceInContent">the example from the spec</A>
+ */
+ @Test
+ public void test32subtree() throws Exception {
+
+ String descri = "3.2 Whitespace in Document Content. (uncommented)";
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/32_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/32_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.3 Start and End Tags
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-SETags">the example from the spec</A>
+ */
+ @Test
+ public void test33subtree() throws Exception {
+
+ String descri = "3.3 Start and End Tags. (uncommented)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/33_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/33_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.4 Character Modifications and Character References
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Chars">the example from the spec</A>
+ */
+ @Test
+ public void test34() throws Exception {
+
+ String descri =
+ "3.4 Character Modifications and Character References. (uncommented)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.4 Character Modifications and Character References (patched to run on validating Parsers)
+ * <p/>
+ * <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119"> The spec</A> states that:
+ * <p/>
+ * Note: The last element, normId, is well-formed but violates a validity
+ * constraint for attributes of type ID. For testing canonical XML
+ * implementations based on validating processors, remove the line
+ * containing this element from the input and canonical form. In general,
+ * XML consumers should be discouraged from using this feature of XML.
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Chars">the example from the spec</A>
+ */
+ @Test
+ public void test34subtree() throws Exception {
+ //todo enable validation
+ String descri =
+ "3.4 Character Modifications and Character References. (uncommented, patched to run on validating Parsers)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_input_validatingParser.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/34_c14n_validatingParser.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.5 Entity References
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-Entities">the example from the spec</A>
+ */
+ @Test
+ public void test35subtree() throws Exception {
+ //todo enable validation
+ String descri = "3.5 Entity References. (uncommented)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/35_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/35_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+ /**
+ * 3.6 UTF-8 Encoding
+ *
+ * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-UTF8">the example from the spec</A>
+ */
+ @Test
+ public void test36subtree() throws Exception {
+
+ String descri = "3.6 UTF-8 Encoding. (uncommented)";
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/36_input.xml");
+ URL fileRef = this.getClass().getClassLoader().getResource("testdata/c14n/in/36_c14n.xml");
+
+ c14nAndCompare(fileIn, fileRef, true);
+ }
+
+// /**
+// * 3.7 Document Subsets
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void test37() throws Exception {
+//
+// String descri = "3.7 Document Subsets. (uncommented)";
+// String fileIn = prefix + "in/37_input.xml";
+// String fileRef = prefix + "in/37_c14n.xml";
+// String fileOut = prefix + "out/xpath_37_output.xml";
+// String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+// boolean validating = true;
+// Element xpath = null;
+// DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+//
+// dfactory.setNamespaceAware(true);
+//
+// DocumentBuilder db = dfactory.newDocumentBuilder();
+// Document doc = db.newDocument();
+//
+// xpath = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_XPATH);
+//
+// xpath.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ietf", "http://www.ietf.org");
+//
+// //J-
+// String xpathFromSpec =
+// "(//. | //@* | //namespace::*)"
+// + "[ "
+// + "self::ietf:e1 or "
+// + "(parent::ietf:e1 and not(self::text() or self::e2)) or "
+// + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) "
+// + "]";
+//
+// //J+
+// xpath.appendChild(doc.createTextNode(xpathFromSpec));
+// assertTrue(descri,
+// c14nAndCompare(fileIn, fileRef, fileOut, c14nURI, validating,
+// xpath));
+// }
+//
+
+ /**
+ * Note: This specification supports the recent XML plenary decision to
+ * deprecate relative namespace URIs as follows: implementations of XML
+ * canonicalization MUST report an operation failure on documents containing
+ * relative namespace URIs. XML canonicalization MUST NOT be implemented
+ * with an XML parser that converts relative URIs to absolute URIs.
+ * <p/>
+ * Implementations MUST report an operation failure on documents containing
+ * relative namespace URIs.
+ */
+ @Test
+ public void testRelativeNSbehaviour() throws Exception {
+
+ URL fileIn = this.getClass().getClassLoader().getResource("testdata/c14n/in/relative-ns-behaviour.xml");
+
+ try {
+ c14nAndCompare(fileIn, fileIn, true);
+ fail();
+ } catch (XMLStreamException cex) {
+ assertTrue(cex != null);
+ }
+ }
+
+// /**
+// * The XPath data model represents data using UCS characters.
+// * Implementations MUST use XML processors that support UTF-8 and UTF-16
+// * and translate to the UCS character domain. For UTF-16, the leading byte
+// * order mark is treated as an artifact of encoding and stripped from the
+// * UCS character data (subsequent zero width non-breaking spaces appearing
+// * within the UTF-16 data are not removed) [UTF-16, Section 3.2]. Support
+// * for ISO-8859-1 encoding is RECOMMENDED, and all other character encodings
+// * are OPTIONAL.
+// *
+// * $todo$ implement the test
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void testTranslationFromUTF16toUTF8() throws Exception {
+//
+// String val =
+// "<UTF16>The german &auml (which is Unicode &#xE4;): "ä"</UTF16>";
+// byte utf16[] = convertToUTF16(val.getBytes());
+// Canonicalizer c14n =
+// Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+// byte c14nBytes[] = c14n.canonicalize(utf16);
+// org.xml.sax.EntityResolver resolver = new TestVectorResolver();
+// InputStream refStream = resolver.resolveEntity(
+// null,
+// prefix + "/in/testTranslationFromUTF16toUTF8.xml")
+// .getByteStream();
+// byte refBytes[] = JavaUtils.getBytesFromStream(refStream);
+// boolean equal = java.security.MessageDigest.isEqual(refBytes, c14nBytes);
+//
+// assertTrue("Parser does not translate to UCS character domain", equal);
+// }
+//
+// /**
+// * Method testXMLAttributes1
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void testXMLAttributes1() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:lang='de'>"
+// + "<notIncluded xml:lang='de'>"
+// + "<notIncluded xml:lang='uk'>"
+// + "<included >"
+// + "</included>"
+// + "</notIncluded>"
+// + "</notIncluded>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"de\">"
+// + "<included xml:lang=\"uk\">"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method testXMLAttributes2
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void testXMLAttributes2() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:lang='uk'>"
+// + "<notIncluded xml:lang='de'>"
+// + "<notIncluded xml:lang='uk'>"
+// + "<included >"
+// + "</included>"
+// + "</notIncluded>"
+// + "</notIncluded>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"uk\">"
+// + "<included xml:lang=\"uk\">"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method testXMLAttributes3
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void testXMLAttributes3() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:lang='de'>"
+// + "<notIncluded xml:lang='de'>"
+// + "<notIncluded xml:lang='uk'>"
+// + "<included xml:lang='de'>"
+// + "</included>"
+// + "</notIncluded>"
+// + "</notIncluded>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"de\">"
+// + "<included xml:lang=\"de\">"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method testXMLAttributes4
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void _testXMLAttributes4() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:lang='de'>"
+// + "<included xml:lang='de'>"
+// + "<notIncluded xml:lang='uk'>"
+// + "<included >"
+// + "</included>"
+// + "</notIncluded>"
+// + "</included>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"de\">"
+// + "<included>"
+// + "<included xml:lang=\"uk\">"
+// + "</included>"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method testXMLAttributes5
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void _testXMLAttributes5() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:lang='de'>"
+// + "<included xml:lang='de'>"
+// + "<notIncluded xml:space='preserve' xml:lang='uk'>"
+// + "<included >"
+// + "</included>"
+// + "</notIncluded>"
+// + "</included>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"de\">"
+// + "<included>"
+// + "<included xml:lang=\"uk\" xml:space=\"preserve\">"
+// + "</included>"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method testXMLAttributes6
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static void _testXMLAttributes6() throws Exception {
+// //J-
+// String input = ""
+// + "<included xml:space='preserve' xml:lang='de'>"
+// + "<included xml:lang='de'>"
+// + "<notIncluded xml:lang='uk'>"
+// + "<included>"
+// + "</included>"
+// + "</notIncluded>"
+// + "</included>"
+// + "</included>";
+//
+// String definedOutput = ""
+// + "<included xml:lang=\"de\" xml:space=\"preserve\">"
+// + "<included>"
+// + "<included xml:lang=\"uk\" xml:space=\"preserve\">"
+// + "</included>"
+// + "</included>"
+// + "</included>";
+// //J+
+// assertTrue(doTestXMLAttributes(input, definedOutput));
+// }
+//
+// /**
+// * Method doTestXMLAttributes
+// *
+// * @param input
+// * @param definedOutput
+// * @param writeResultsToFile
+// *
+// * @throws CanonicalizationException
+// * @throws java.io.FileNotFoundException
+// * @throws java.io.IOException
+// * @throws InvalidCanonicalizerException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerException
+// */
+// private static boolean doTestXMLAttributes(
+// String input, String definedOutput) throws Exception {
+//
+// DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+//
+// dfactory.setNamespaceAware(true);
+// dfactory.setValidating(true);
+//
+// DocumentBuilder db = dfactory.newDocumentBuilder();
+//
+// db.setErrorHandler(new org.apache.xml.security.utils
+// .IgnoreAllErrorHandler());
+//
+// Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
+// Canonicalizer c14nizer =
+// Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
+// CachedXPathAPI xpathAPI = new CachedXPathAPI();
+//
+// //XMLUtils.circumventBug2650(doc);
+//
+// NodeList nodes =
+// xpathAPI.selectNodeList(doc, "(//*[local-name()='included'] | //@*[parent::node()[local-name()='included']])");
+// byte result[] = c14nizer.canonicalizeXPathNodeSet(nodes);
+// byte defined[] = definedOutput.getBytes();
+// assertEquals(definedOutput, new String(result));
+// return java.security.MessageDigest.isEqual(defined, result);
+// }
+
+ /**
+ * Method c14nAndCompare
+ */
+ private void c14nAndCompare(
+ URL fileIn, URL fileRef, boolean ommitComments) throws Exception {
+
+ CanonicalizerBase canonicalizerBase;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ if (ommitComments) {
+ canonicalizerBase = new Canonicalizer20010315_OmitCommentsTransformer(null, baos);
+ } else {
+ canonicalizerBase = new Canonicalizer20010315_WithCommentsTransformer(null, baos);
+ }
+
+ XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(fileIn.openStream());
+ while (xmlEventReader.hasNext()) {
+ XMLEvent xmlEvent = xmlEventReader.nextEvent();
+ canonicalizerBase.transform(xmlEvent);
+ }
+
+ // org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
+ // byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
+ byte refBytes[] = getBytesFromResource(fileRef);
+
+ // if everything is OK, result is true; we do a binary compare, byte by byte
+ boolean result = java.security.MessageDigest.isEqual(refBytes, baos.toByteArray());
+ if (!result) {
+ assertEquals(new String(baos.toByteArray()), new String(refBytes));
+ }
+ assertTrue(result);
+ }
+
+
+ public static byte[] getBytesFromResource(URL resource) throws IOException {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ InputStream inputStream = resource.openStream();
+ try {
+ byte buf[] = new byte[1024];
+ int len;
+ while ((len = inputStream.read(buf)) > 0) {
+ baos.write(buf, 0, len);
+ }
+
+ return baos.toByteArray();
+ } finally {
+ inputStream.close();
+ }
+ }
+
+// /**
+// * This method takes the input bytes as XML Document and converts it to an
+// * UTF-16 encoded XML document which is serialized to byte[] and returned.
+// *
+// * @param input
+// *
+// * @throws java.io.IOException
+// * @throws javax.xml.parsers.ParserConfigurationException
+// * @throws org.xml.sax.SAXException
+// * @throws javax.xml.transform.TransformerConfigurationException
+// * @throws javax.xml.transform.TransformerException
+// */
+// public static byte[] convertToUTF16(byte input[]) throws Exception {
+//
+// //String ENCODING_ISO8859_1 = "ISO-8859-1";
+// //String ENCODING_UTF8 = "UTF-8";
+// String ENCODING_UTF16 = "UTF-16";
+// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+// DocumentBuilder db = dbf.newDocumentBuilder();
+// Document doc = db.parse(new ByteArrayInputStream(input));
+// TransformerFactory tFactory = TransformerFactory.newInstance();
+// Transformer transformer = tFactory.newTransformer();
+//
+// transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING_UTF16);
+// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+//
+// DOMSource source = new DOMSource(doc);
+// ByteArrayOutputStream os = new ByteArrayOutputStream();
+// StreamResult result = new StreamResult(os);
+//
+// transformer.transform(source, result);
+//
+// return os.toByteArray();
+// }
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/Canonicalizer20010315Test.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision
Added: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/DerivedKeyTokenTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/DerivedKeyTokenTest.java?rev=1172285&view=auto
==============================================================================
--- webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/DerivedKeyTokenTest.java (added)
+++ webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/DerivedKeyTokenTest.java Sun Sep 18 13:51:23 2011
@@ -0,0 +1,722 @@
+/**
+ * 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.swssf.test;
+
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.components.crypto.CryptoFactory;
+import org.apache.ws.security.components.crypto.CryptoType;
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.message.*;
+import org.apache.ws.security.message.token.SecurityTokenReference;
+import org.swssf.WSSec;
+import org.swssf.ext.Constants;
+import org.swssf.ext.InboundWSSec;
+import org.swssf.ext.OutboundWSSec;
+import org.swssf.ext.SecurityProperties;
+import org.swssf.securityEvent.SecurityEvent;
+import org.swssf.test.utils.SOAPUtil;
+import org.swssf.test.utils.StAX2DOM;
+import org.swssf.test.utils.XmlReaderToWriter;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+
+/**
+ * @author $Author$
+ * @version $Revision$ $Date$
+ */
+public class DerivedKeyTokenTest extends AbstractTestBase {
+
+ @BeforeClass
+ public void setUp() throws Exception {
+ WSSConfig.init();
+ }
+
+ @Test
+ public void testEncryptionDecryptionTRIPLEDESOutbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ byte[] secret = new byte[128 / 8];
+ Constants.secureRandom.nextBytes(secret);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(secret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc");
+ securityProperties.setEncryptionKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_soap11_Body.getLocalPart());
+ }
+ {
+ String action = WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testEncryptionDecryptionTRIPLEDESInbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ //EncryptedKey
+ WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+ encrKeyBuilder.setUserInfo("receiver");
+ encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ encrKeyBuilder.prepare(doc, crypto);
+
+ //Key information from the EncryptedKey
+ byte[] ek = encrKeyBuilder.getEphemeralKey();
+ String tokenIdentifier = encrKeyBuilder.getId();
+
+ //Derived key encryption
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
+ encrBuilder.setExternalKey(ek, tokenIdentifier);
+ encrBuilder.build(doc, secHeader);
+
+ encrKeyBuilder.prependToHeader(secHeader);
+ encrKeyBuilder.prependBSTElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testEncryptionDecryptionAES128Outbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ byte[] secret = new byte[128 / 8];
+ Constants.secureRandom.nextBytes(secret);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(secret);
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setEncryptionSymAlgorithm("http://www.w3.org/2001/04/xmlenc#aes128-cbc");
+ securityProperties.setEncryptionKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_soap11_Body.getLocalPart());
+ }
+ {
+ String action = WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testEncryptionDecryptionAES128Inbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ sctBuilder.prepare(doc, crypto);
+
+ //EncryptedKey
+ WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+ encrKeyBuilder.setUserInfo("receiver");
+ encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ encrKeyBuilder.prepare(doc, crypto);
+
+ //Key information from the EncryptedKey
+ byte[] ek = encrKeyBuilder.getEphemeralKey();
+ String tokenIdentifier = encrKeyBuilder.getId();
+
+ //Derived key encryption
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(ek, tokenIdentifier);
+ encrBuilder.build(doc, secHeader);
+
+ encrKeyBuilder.prependToHeader(secHeader);
+ encrKeyBuilder.prependBSTElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testSignatureOutbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl();
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.setEncryptionKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+ securityProperties.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#hmac-sha1");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.EncryptedKey);
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+ }
+ {
+ String action = WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testSignatureInbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ //EncryptedKey
+ WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+ encrKeyBuilder.setUserInfo("receiver");
+ encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ encrKeyBuilder.prepare(doc, crypto);
+
+ //Key information from the EncryptedKey
+ byte[] ek = encrKeyBuilder.getEphemeralKey();
+ String tokenIdentifier = encrKeyBuilder.getId();
+
+ //Derived key encryption
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(ek, tokenIdentifier);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ encrKeyBuilder.prependToHeader(secHeader);
+ encrKeyBuilder.prependBSTElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ }
+
+ @Test
+ public void testSignatureThumbprintSHA1Outbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl();
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#hmac-sha1");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.DirectReference);
+ securityProperties.setDerivedKeyKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsse_KeyIdentifier.getNamespaceURI(), Constants.TAG_wsse_KeyIdentifier.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Attr attr = (Attr) nodeList.item(0).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_THUMBPRINT);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ {
+ String action = WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testSignatureThumbprintSHA1Inbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ SecurityTokenReference secToken = new SecurityTokenReference(doc);
+ CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+ cryptoType.setAlias("transmitter");
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
+ secToken.setKeyIdentifierThumb(certs[0]);
+
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ java.security.Key key = crypto.getPrivateKey("transmitter", "default");
+ sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ sigBuilder.prependDKElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ }
+
+ @Test
+ public void testSignatureSKIOutbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl();
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#hmac-sha1");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.DirectReference);
+ securityProperties.setDerivedKeyKeyIdentifierType(Constants.KeyIdentifierType.SKI_KEY_IDENTIFIER);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsse_KeyIdentifier.getNamespaceURI(), Constants.TAG_wsse_KeyIdentifier.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ Attr attr = (Attr) nodeList.item(0).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_X509SubjectKeyIdentifier);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ {
+ String action = WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testSignatureSKIInbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ SecurityTokenReference secToken = new SecurityTokenReference(doc);
+ CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+ cryptoType.setAlias("transmitter");
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+ X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
+ secToken.setKeyIdentifierSKI(certs[0], crypto);
+
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ java.security.Key key = crypto.getPrivateKey("transmitter", "default");
+ sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ sigBuilder.prependDKElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("transmitter.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ }
+
+ @Test
+ public void testSignatureEncryptOutbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.SIGNATURE_WITH_DERIVED_KEY, Constants.Action.ENCRYPT_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl();
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#hmac-sha1");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setEncryptionKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.EncryptedKey);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsse_KeyIdentifier.getNamespaceURI(), Constants.TAG_wsse_KeyIdentifier.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ Attr attr = (Attr) nodeList.item(0).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_THUMBPRINT);
+ attr = (Attr) nodeList.item(1).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_THUMBPRINT);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ {
+ String action = WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testSignatureEncryptInbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+
+ //EncryptedKey
+ WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+ encrKeyBuilder.setUserInfo("receiver");
+ encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ encrKeyBuilder.prepare(doc, crypto);
+
+ //Key information from the EncryptedKey
+ byte[] ek = encrKeyBuilder.getEphemeralKey();
+ String tokenIdentifier = encrKeyBuilder.getId();
+
+ //Derived key encryption
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(ek, tokenIdentifier);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ Document signedDoc = sigBuilder.build(doc, secHeader);
+
+ //Derived key signature
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(ek, tokenIdentifier);
+ encrBuilder.build(signedDoc, secHeader);
+
+ encrKeyBuilder.prependToHeader(secHeader);
+ encrKeyBuilder.prependBSTElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ nodeList = doc.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+
+ @Test
+ public void testEncryptSignatureOutbound() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ Constants.Action[] actions = new Constants.Action[]{Constants.Action.ENCRYPT_WITH_DERIVED_KEY, Constants.Action.SIGNATURE_WITH_DERIVED_KEY};
+ securityProperties.setOutAction(actions);
+ CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl();
+ securityProperties.setCallbackHandler(callbackHandler);
+ securityProperties.setSignatureAlgorithm("http://www.w3.org/2000/09/xmldsig#hmac-sha1");
+ securityProperties.loadSignatureKeyStore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setSignatureUser("receiver");
+ securityProperties.loadEncryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setEncryptionUser("receiver");
+ securityProperties.setEncryptionKeyIdentifierType(Constants.KeyIdentifierType.THUMBPRINT_IDENTIFIER);
+ securityProperties.setDerivedKeyTokenReference(Constants.DerivedKeyTokenReference.EncryptedKey);
+
+ OutboundWSSec wsSecOut = WSSec.getOutboundWSSec(securityProperties);
+ XMLStreamWriter xmlStreamWriter = wsSecOut.processOutMessage(baos, "UTF-8", new ArrayList<SecurityEvent>());
+ XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml"));
+ XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
+ xmlStreamWriter.close();
+
+ Document document = documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray()));
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.item(0).getParentNode().getLocalName(), Constants.TAG_wsse_Security.getLocalPart());
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_SecurityContextToken.getNamespaceURI(), Constants.TAG_wsc0502_SecurityContextToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedKey.getNamespaceURI(), Constants.TAG_xenc_EncryptedKey.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsc0502_DerivedKeyToken.getNamespaceURI(), Constants.TAG_wsc0502_DerivedKeyToken.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_wsse_KeyIdentifier.getNamespaceURI(), Constants.TAG_wsse_KeyIdentifier.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 2);
+ Attr attr = (Attr) nodeList.item(0).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_THUMBPRINT);
+ attr = (Attr) nodeList.item(1).getAttributes().getNamedItem(Constants.ATT_NULL_ValueType.getLocalPart());
+ Assert.assertEquals(attr.getValue(), Constants.NS_THUMBPRINT);
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+ }
+ {
+ String action = WSHandlerConstants.ENCRYPT + " " + WSHandlerConstants.SIGNATURE;
+ doInboundSecurityWithWSS4J(documentBuilderFactory.newDocumentBuilder().parse(new ByteArrayInputStream(baos.toByteArray())), action);
+ }
+ }
+
+ @Test
+ public void testEncryptSignatureInbound() throws Exception {
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ {
+ Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ Crypto crypto = CryptoFactory.getInstance("transmitter-crypto.properties");
+
+ //EncryptedKey
+ WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+ encrKeyBuilder.setUserInfo("receiver");
+ encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ encrKeyBuilder.prepare(doc, crypto);
+
+ //Key information from the EncryptedKey
+ byte[] ek = encrKeyBuilder.getEphemeralKey();
+ String tokenIdentifier = encrKeyBuilder.getId();
+
+ //Derived key signature
+ WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+ encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+ encrBuilder.setExternalKey(ek, tokenIdentifier);
+ encrBuilder.build(doc, secHeader);
+
+ //Derived key encryption
+ WSSecDKSign sigBuilder = new WSSecDKSign();
+ sigBuilder.setExternalKey(ek, tokenIdentifier);
+ sigBuilder.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
+ sigBuilder.build(doc, secHeader);
+
+ encrKeyBuilder.prependToHeader(secHeader);
+ encrKeyBuilder.prependBSTElementToHeader(secHeader);
+
+ NodeList nodeList = doc.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ nodeList = doc.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ javax.xml.transform.Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+ transformer.transform(new DOMSource(doc), new StreamResult(baos));
+ }
+
+ {
+ SecurityProperties securityProperties = new SecurityProperties();
+ securityProperties.loadSignatureVerificationKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.loadDecryptionKeystore(this.getClass().getClassLoader().getResource("receiver.jks"), "default".toCharArray());
+ securityProperties.setCallbackHandler(new CallbackHandlerImpl());
+ InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+ XMLStreamReader xmlStreamReader = wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray())));
+
+ Document document = StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), xmlStreamReader);
+
+ NodeList nodeList = document.getElementsByTagNameNS(Constants.TAG_dsig_Signature.getNamespaceURI(), Constants.TAG_dsig_Signature.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 1);
+
+ nodeList = document.getElementsByTagNameNS(Constants.TAG_xenc_EncryptedData.getNamespaceURI(), Constants.TAG_xenc_EncryptedData.getLocalPart());
+ Assert.assertEquals(nodeList.getLength(), 0);
+ }
+ }
+}
Propchange: webservices/wss4j/branches/swssf/streaming-ws-security/src/test/java/org/swssf/test/DerivedKeyTokenTest.java
------------------------------------------------------------------------------
svn:keywords = Author Date Id Revision