You are viewing a plain text version of this content. The canonical link for it is here.
Posted to wss4j-dev@ws.apache.org by ru...@apache.org on 2006/03/25 07:13:06 UTC

svn commit: r388712 - in /webservices/wss4j/trunk: src/org/apache/ws/security/ src/org/apache/ws/security/message/ src/org/apache/ws/security/message/token/ src/org/apache/ws/security/processor/ src/org/apache/ws/security/util/ test/wssec/

Author: ruchithf
Date: Fri Mar 24 22:13:04 2006
New Revision: 388712

URL: http://svn.apache.org/viewcvs?rev=388712&view=rev
Log:
- A builder and a processer added to handle SecurityContextToken (from WS-SecureConversation)
- Testcase added
- Imported the UUIDGenerator from Axis2 codebase
- Modified the WSPasswordCallback to include the SECURITY_CONTEXT_TOKEN usage


Added:
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecSecurityContextToken.java
    webservices/wss4j/trunk/src/org/apache/ws/security/message/token/SecurityContextToken.java
    webservices/wss4j/trunk/src/org/apache/ws/security/processor/SecurityContextTokenProcessor.java
    webservices/wss4j/trunk/src/org/apache/ws/security/util/UUIDGenerator.java
    webservices/wss4j/trunk/test/wssec/TestWSSecurityNewSCT.java
Modified:
    webservices/wss4j/trunk/src/org/apache/ws/security/WSPasswordCallback.java
    webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java
    webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java
    webservices/wss4j/trunk/src/org/apache/ws/security/errors.properties
    webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
    webservices/wss4j/trunk/test/wssec/PackageTests.java

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSPasswordCallback.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSPasswordCallback.java?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSPasswordCallback.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSPasswordCallback.java Fri Mar 24 22:13:04 2006
@@ -49,12 +49,14 @@
  * decrypt parts of the SOAP request. Note, the key must match the
  * symmetric encryption/decryption algorithm specified (refer to
  * {@link org.apache.ws.security.handler.WSHandlerConstants#ENC_SYM_ALGO}).</li>
- * * <li><code>USERNAME_TOKEN_UNKNOWN</code> - either an not specified 
+ * <li><code>USERNAME_TOKEN_UNKNOWN</code> - either an not specified 
  * password type or a password type passwordText. In these both cases <b>only</b>
- * the password variable is <b>set</>. The callback class now may check if
+ * the password variable is <b>set</b>. The callback class now may check if
  * the username and password match. If they don't match the callback class must
  * throw an exception. The exception can be a UnsupportedCallbackException or
  * an IOException.</li>
+ * <li><code>SECURITY_CONTEXT_TOKEN</code> - need the key to to be associated 
+ * with a <code>wsc:SecurityContextToken</code>.</li>
  * </ul>
  *
  * @author Werner Dittmann (Werner.Dittmann@siemens.com).
@@ -68,6 +70,7 @@
     public static final int SIGNATURE = 3;
     public static final int KEY_NAME = 4;
     public static final int USERNAME_TOKEN_UNKNOWN = 5;
+    public final static int SECURITY_CONTEXT_TOKEN = 6; 
 
     private String identifier;
     private String password;

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java Fri Mar 24 22:13:04 2006
@@ -17,18 +17,17 @@
 
 package org.apache.ws.security;
 
+import java.util.HashMap;
+
+import javax.xml.namespace.QName;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.ws.security.transform.STRTransform;
-import org.apache.ws.security.util.Loader;
 import org.apache.ws.security.action.Action;
 import org.apache.ws.security.processor.Processor;
+import org.apache.ws.security.transform.STRTransform;
+import org.apache.ws.security.util.Loader;
 import org.apache.xml.security.transforms.Transform;
-import org.apache.xml.security.algorithms.JCEMapper;
-
-import java.util.HashMap;
-
-import javax.xml.namespace.QName;
 
 /**
  * WSSConfig <p/> Carries configuration data so the WSS4J spec compliance can be
@@ -248,6 +247,8 @@
             name = "org.apache.ws.security.processor.SignatureConfirmationProcessor";
         } else if (el.equals(WSSecurityEngine.DERIVED_KEY_TOKEN)) {
             name = "org.apache.ws.security.processor.DerivedKeyTokenProcessor";
+        } else if(el.equals(WSSecurityEngine.SECURITY_CONTEXT_TOKEN)) {
+            name = "org.apache.ws.security.processor.SecurityContextTokenProcessor";
         }
 
         if (name != null) {

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java Fri Mar 24 22:13:04 2006
@@ -90,6 +90,11 @@
      */
     public static final QName DERIVED_KEY_TOKEN = new QName(ConversationConstants.WSC_NS, ConversationConstants.DERIVED_KEY_TOKEN_LN);
 
+    /**
+     * <code>wsc:SecurityContextToken</code> as defined by WS-SecureConversation specification
+     */
+    public static final QName SECURITY_CONTEXT_TOKEN = new QName(ConversationConstants.WSC_NS, ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
+    
     public WSSecurityEngine() {
     }
 

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/errors.properties
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/errors.properties?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/errors.properties (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/errors.properties Fri Mar 24 22:13:04 2006
@@ -49,6 +49,7 @@
 noDecCryptoFile=WSSecurityEngine: No crypto propery file supplied for decryption
 noCallback=WSSecurityEngine: No password callback supplied
 noPassword=WSSecurityEngine: Callback supplied no password for: {0}
+noKey=WSSecurityEngine: Callback supplied no key for: {0}
 noEncAlgo=WSSecurityEngine: xenc:EncryptedKey does not contain xenc:EncryptionMethod/@Algorithm
 unsupportedKeyTransp=unsupported key transport encryption algorithm: {0}
 noCipher=WSSecurityEngine: EncryptedKey does not contain xenc:CipherData/xenc:CipherValue

Added: webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecSecurityContextToken.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecSecurityContextToken.java?rev=388712&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecSecurityContextToken.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecSecurityContextToken.java Fri Mar 24 22:13:04 2006
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ws.security.message;
+
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.token.SecurityContextToken;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.w3c.dom.Document;
+
+/**
+ * Builder class to add a <code>wsc:SecurityContextToken</code> into the
+ * <code>wsse:Security</code>
+ * 
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public class WSSecSecurityContextToken {
+
+    /**
+     * The <code>wsc:SecurityContextToken</code> to be added to the
+     * <code>wsse:SecurityHeader</code>
+     */
+    private SecurityContextToken sct;
+
+    /**
+     * The <code>wsu:Id</code> of the <code>wsc:SecurityContextToken</code> 
+     */
+    private String sctId;
+
+    /**
+     * The <code>wsc:Identifier</code> of the
+     * <code>wsc:SecurityContextToken</code>
+     */
+    private String identifier;
+
+    /**
+     * The symmetric secret associated with the SecurityContextToken
+     */
+    protected byte[] secret;
+
+    public Document build(Document doc, Crypto crypto, WSSecHeader secHeader)
+            throws WSSecurityException {
+        this.prepare(doc, crypto);
+        return doc;
+    }
+
+    protected void prepare(Document doc, Crypto crypto)
+            throws WSSecurityException {
+
+        if (sct == null) {
+            if (this.identifier != null) {
+                this.sct = new SecurityContextToken(doc, this.identifier);
+            } else {
+                this.sct = new SecurityContextToken(doc);
+                this.identifier = this.sct.getIdentifier();
+            }
+        }
+
+        // The wsu:Id of the wsc:SecurityContextToken
+        if (this.sctId == null) {
+            this.sctId = "sctid-" + this.sct.getElement().hashCode();
+        }
+        this.sct.setID(this.sctId);
+
+    }
+
+    public void commit(Document doc, Crypto crypto, WSSecHeader secHeader)
+            throws WSSecurityException {
+        WSSecurityUtil.prependChildElement(doc, secHeader.getSecurityHeader(),
+                sct.getElement(), false);
+    }
+
+    /**
+     * @return Returns the sct.
+     */
+    public SecurityContextToken getSct() {
+        return sct;
+    }
+
+    /**
+     * @param sct
+     *            The sct to set.
+     */
+    public void setSct(SecurityContextToken sct) {
+        this.sct = sct;
+    }
+
+    /**
+     * @return Returns the ephemeralKey.
+     */
+    public byte[] getSecret() {
+        return secret;
+    }
+
+    /**
+     * @param ephemeralKey
+     *            The ephemeralKey to set.
+     */
+    protected void setSecret(byte[] ephemeralKey) {
+        this.secret = ephemeralKey;
+    }
+
+    /**
+     * @return Returns the identifier.
+     */
+    public String getIdentifier() {
+        return identifier;
+    }
+
+    /**
+     * @param identifier The identifier to set.
+     */
+    public void setIdentifier(String identifier) {
+        this.identifier = identifier;
+    }
+
+    /**
+     * @return Returns the sctId.
+     */
+    public String getSctId() {
+        return sctId;
+    }
+
+    /**
+     * @param sctId The sctId to set.
+     */
+    public void setSctId(String sctId) {
+        this.sctId = sctId;
+    }
+    
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/message/token/SecurityContextToken.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/token/SecurityContextToken.java?rev=388712&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/token/SecurityContextToken.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/token/SecurityContextToken.java Fri Mar 24 22:13:04 2006
@@ -0,0 +1,178 @@
+package org.apache.ws.security.message.token;
+
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.util.DOM2Writer;
+import org.apache.ws.security.util.UUIDGenerator;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+import javax.xml.namespace.QName;
+
+/**
+ * @author Ruchith Fernando
+ * @version 1.0
+ */
+public class SecurityContextToken {
+
+    public static final QName TOKEN = new QName(ConversationConstants.WSC_NS,
+            ConversationConstants.
+            SECURITY_CONTEXT_TOKEN_LN);
+
+    /**
+     * Security context token element
+     */
+    protected Element element = null;
+
+    /**
+     * Identifier element
+     */
+    protected Element elementIdentifier = null;
+
+    /**
+     * Constructor to create the SCT
+     *
+     * @param doc
+     */
+    public SecurityContextToken(Document doc) {
+
+        this.element = doc.createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" + ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
+
+        WSSecurityUtil.setNamespace(this.element, ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+
+        this.elementIdentifier = doc.createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" + ConversationConstants.IDENTIFIER_LN);
+
+        this.element.appendChild(this.elementIdentifier);
+
+        String uuid = UUIDGenerator.getUUID();
+
+        this.elementIdentifier.appendChild(doc.createTextNode(uuid));
+    }
+
+    /**
+     * Constructor to create the SCT with a given uuid
+     *
+     * @param doc
+     */
+    public SecurityContextToken(Document doc, String uuid) {
+
+        this.element = doc.createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" + ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
+
+        WSSecurityUtil.setNamespace(this.element, ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+
+        this.elementIdentifier = doc.createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" + ConversationConstants.IDENTIFIER_LN);
+
+        this.element.appendChild(this.elementIdentifier);
+
+        this.elementIdentifier.appendChild(doc.createTextNode(uuid));
+    }
+
+    /**
+     * This is used to create a SecurityContestToken using a DOM Element
+     *
+     * @param elem The DOM element: The security context token
+     * @throws WSSecurityException If the element passed in in not a security context token
+     */
+    public SecurityContextToken(Element elem) throws WSSecurityException {
+        this.element = elem;
+        QName el = new QName(this.element.getNamespaceURI(),
+                this.element.getLocalName());
+        if (!el.equals(TOKEN)) {    // If the element is not a security context token
+            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
+                    new Object[]{el});
+        }
+        this.elementIdentifier = (Element) WSSecurityUtil.getDirectChild(element, ConversationConstants.IDENTIFIER_LN, ConversationConstants.WSC_NS);
+    }
+
+    /**
+     * Set the identifier.
+     *
+     * @param name sets a text node containing the identifier into
+     *             the identifier element.
+     */
+    public void setIdentifier(Document doc, String uuid) {
+        Text node = getFirstNode(this.elementIdentifier);
+        node.setData(uuid);
+    }
+
+    /**
+     * Get the identifier.
+     *
+     * @return the data from the identifier element.
+     */
+    public String getIdentifier() {
+        if (this.elementIdentifier != null) {
+            //System.out.println("In !=null "+ this.elementIdentifier.getFirstChild().toString());
+            return getFirstNode(this.elementIdentifier).getData();
+        }
+        return null;
+    }
+
+    public void setElement(Element elem) {
+        this.element.appendChild(elem);
+    }
+
+    /**
+     * Returns the first text node of an element.
+     *
+     * @param e the element to get the node from
+     * @return the first text node or <code>null</code> if node
+     *         is null or is not a text node
+     */
+    private Text getFirstNode(Element e) {
+        Node node = e.getFirstChild();
+        return ((node != null) && node instanceof Text) ? (Text) node : null;
+    }
+
+    /**
+     * Returns the dom element of this <code>SecurityContextToken</code> object.
+     *
+     * @return the <code>wsse:UsernameToken</code> element
+     */
+    public Element getElement() {
+        return this.element;
+    }
+
+    /**
+     * Returns the string representation of the token.
+     *
+     * @return a XML string representation
+     */
+    public String toString() {
+        return DOM2Writer.nodeToString((Node) this.element);
+    }
+
+    /**
+     * Gets the id.
+     *
+     * @return the value of the <code>wsu:Id</code> attribute of this
+     *         SecurityContextToken
+     */
+    public String getID() {
+        return this.element.getAttributeNS(WSConstants.WSU_NS, "Id");
+    }
+
+    /**
+     * Set the id of this security context token.
+     *
+     * @param id the value for the <code>wsu:Id</code> attribute of this
+     *           SecurityContextToken
+     */
+    public void setID(String id) {
+        String prefix = WSSecurityUtil.setNamespace(this.element,
+                WSConstants.WSU_NS,
+                WSConstants.WSU_PREFIX);
+        this.element.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
+    }
+
+}

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java Fri Mar 24 22:13:04 2006
@@ -17,10 +17,6 @@
 
 package org.apache.ws.security.processor;
 
-import java.util.Vector;
-
-import javax.security.auth.callback.CallbackHandler;
-
 import org.apache.ws.security.WSDocInfo;
 import org.apache.ws.security.WSSConfig;
 import org.apache.ws.security.WSSecurityException;
@@ -34,8 +30,13 @@
 import org.apache.ws.security.util.Base64;
 import org.w3c.dom.Element;
 
+import javax.security.auth.callback.CallbackHandler;
+
+import java.util.Vector;
+
 /**
- *
+ * The processor to process <code>wsc:DerivedKeyToken</code>.
+ * 
  * @author Ruchith Fernando (ruchith.fernando@gmail.com)
  */
 public class DerivedKeyTokenProcessor implements Processor {
@@ -104,23 +105,26 @@
      * @param dkt
      * @throws WSSecurityException
      */
-    private void extractSecret(WSDocInfo wsDocInfo, DerivedKeyToken dkt) throws WSSecurityException {
+    private void extractSecret(WSDocInfo wsDocInfo, DerivedKeyToken dkt)
+            throws WSSecurityException {
         SecurityTokenReference str = dkt.getSecuityTokenReference();
-        if(str != null) {
+        if (str != null) {
             Reference ref = str.getReference();
             String uri = ref.getURI();
             Processor processor = wsDocInfo.getProcessor(uri.substring(1));
-            if(processor instanceof EncryptedKeyProcessor) {
-                this.secret = ((EncryptedKeyProcessor)processor).getDecryptedBytes();
-            }
-            else  {
+            if (processor instanceof EncryptedKeyProcessor) {
+                this.secret = ((EncryptedKeyProcessor) processor)
+                        .getDecryptedBytes();
+            } else if (processor instanceof SecurityContextTokenProcessor) {
+                this.secret = ((SecurityContextTokenProcessor) processor)
+                        .getSecret();
+            } else {
                 throw new WSSecurityException(
                         WSSecurityException.FAILED_ENC_DEC, "unsupportedKeyId");
             }
-        }
-        else {
+        } else {
             throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
-            "noReference");
+                    "noReference");
         }
     }
 

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/SecurityContextTokenProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/SecurityContextTokenProcessor.java?rev=388712&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/SecurityContextTokenProcessor.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/SecurityContextTokenProcessor.java Fri Mar 24 22:13:04 2006
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ws.security.processor;
+
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.token.SecurityContextToken;
+import org.w3c.dom.Element;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import java.io.IOException;
+import java.util.Vector;
+
+/**
+ * The processor to process <code>wsc:SecurityContextToken</code>.
+ * 
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public class SecurityContextTokenProcessor implements Processor {
+
+    /**
+     * The <code>wsi:ID</code> of the <code>wsc:SecurityContextToken</code>
+     * element.
+     */
+    private String sctId;
+
+    /**
+     * The secret associated with the <code>wsc:SecurityContextToken</code>.
+     */
+    private byte[] secret;
+
+    /**
+     * The <code>wsc:Identifier</code> of the
+     * <code>wsc:SecurityContextToken</code> element.
+     */
+    private String identifier;
+
+    public void handleToken(Element elem, Crypto crypto, Crypto decCrypto,
+            CallbackHandler cb, WSDocInfo wsDocInfo, Vector returnResults,
+            WSSConfig config) throws WSSecurityException {
+
+        SecurityContextToken sct = new SecurityContextToken(elem);
+        this.identifier = sct.getIdentifier();
+        this.secret = this.getSecret(cb, sct);
+        this.sctId = sct.getID();
+    }
+
+    /**
+     * Get the secret from the provided callback handler and return it.
+     * 
+     * @param cb
+     * @param sct
+     * @return The key collected using the callback handler
+     */
+    private byte[] getSecret(CallbackHandler cb, SecurityContextToken sct)
+            throws WSSecurityException {
+
+        if (cb == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "noCallback");
+        }
+
+        WSPasswordCallback callback = new WSPasswordCallback(sct
+                .getIdentifier(), WSPasswordCallback.SECURITY_CONTEXT_TOKEN);
+        Callback[] callbacks = new Callback[1];
+        callbacks[0] = callback;
+        try {
+            cb.handle(callbacks);
+        } catch (IOException e) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
+                    new Object[] { sct.getIdentifier() });
+        } catch (UnsupportedCallbackException e) {
+            throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
+                    new Object[] { sct.getIdentifier() });
+        }
+
+        return callback.getKey();
+    }
+
+    /**
+     * Return the id of the 
+     */
+    public String getId() {
+        return this.sctId;
+    }
+
+    /**
+     * @return Returns the identifier.
+     */
+    public String getIdentifier() {
+        return identifier;
+    }
+
+    /**
+     * @return Returns the secret.
+     */
+    public byte[] getSecret() {
+        return secret;
+    }
+
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/util/UUIDGenerator.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/util/UUIDGenerator.java?rev=388712&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/util/UUIDGenerator.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/util/UUIDGenerator.java Fri Mar 24 22:13:04 2006
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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.ws.security.util;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Date;
+import java.util.Random;
+
+/**
+ * UUID generator (taken from Axis2) 
+ */
+public class UUIDGenerator {
+
+    private static String baseUUID = null;
+    private static long incrementingValue = 0;
+
+
+    private static Random myRand = null;
+
+    /**
+     * MD5 a random string with localhost/date etc will return 128 bits
+     * construct a string of 18 characters from those bits.
+     *
+     * @return string
+     */
+    public static String getUUID() {
+        if (baseUUID == null) {
+            baseUUID = getInitialUUID();
+        }
+        if(++incrementingValue >= Long.MAX_VALUE){
+            incrementingValue = 0;
+        }
+        return "urn:uuid:" + baseUUID + new Date().getTime() + incrementingValue;
+    }
+
+    protected static String getInitialUUID() {
+        if (myRand == null) {
+            myRand = new Random();
+        }
+        long rand = myRand.nextLong();
+        String sid;
+        try {
+            sid = InetAddress.getLocalHost().toString();
+        } catch (UnknownHostException e) {
+            sid = Thread.currentThread().getName();
+        }
+        StringBuffer sb = new StringBuffer();
+        sb.append(sid);
+        sb.append(":");
+        sb.append(Long.toString(rand));
+        MessageDigest md5 = null;
+        try {
+            md5 = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException e) {
+            //System.out.println("Error: " + e);
+            //todo heve to be properly handle
+        }
+        md5.update(sb.toString().getBytes());
+        byte[] array = md5.digest();
+        StringBuffer sb2 = new StringBuffer();
+        for (int j = 0; j < array.length; ++j) {
+            int b = array[j] & 0xFF;
+            sb2.append(Integer.toHexString(b));
+        }
+        int begin = myRand.nextInt();
+        if (begin < 0) begin = begin * -1;
+        begin = begin % 8;
+        return sb2.toString().substring(begin, begin + 18).toUpperCase();
+    }
+
+}

Modified: webservices/wss4j/trunk/test/wssec/PackageTests.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/test/wssec/PackageTests.java?rev=388712&r1=388711&r2=388712&view=diff
==============================================================================
--- webservices/wss4j/trunk/test/wssec/PackageTests.java (original)
+++ webservices/wss4j/trunk/test/wssec/PackageTests.java Fri Mar 24 22:13:04 2006
@@ -69,6 +69,7 @@
         suite.addTestSuite(TestWSSecurityNewST2.class);
         suite.addTestSuite(TestWSSecurityNewST3.class);
         suite.addTestSuite(TestWSSecurityNewDK.class);
+        suite.addTestSuite(TestWSSecurityNewSCT.class);
         return suite;
     }
 

Added: webservices/wss4j/trunk/test/wssec/TestWSSecurityNewSCT.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/test/wssec/TestWSSecurityNewSCT.java?rev=388712&view=auto
==============================================================================
--- webservices/wss4j/trunk/test/wssec/TestWSSecurityNewSCT.java (added)
+++ webservices/wss4j/trunk/test/wssec/TestWSSecurityNewSCT.java Fri Mar 24 22:13:04 2006
@@ -0,0 +1,209 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed 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 wssec;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.SecureRandom;
+import java.util.Hashtable;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import junit.framework.TestCase;
+
+import org.apache.axis.Message;
+import org.apache.axis.MessageContext;
+import org.apache.axis.client.AxisClient;
+import org.apache.axis.configuration.NullProvider;
+import org.apache.axis.message.SOAPEnvelope;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSecurityEngine;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.components.crypto.CryptoFactory;
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.message.WSSecDKEncrypt;
+import org.apache.ws.security.message.WSSecHeader;
+import org.apache.ws.security.message.WSSecSecurityContextToken;
+import org.w3c.dom.Document;
+
+/**
+ * Testcase to test WSSecSecurityContextToken
+ * 
+ * @see org.apache.ws.security.message.WSSecSecurityContextToken
+ * 
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public class TestWSSecurityNewSCT extends TestCase implements CallbackHandler {
+
+    static final String soapMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+            + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+            + "   <soapenv:Body>"
+            + "      <ns1:testMethod xmlns:ns1=\"uri:LogTestService2\"></ns1:testMethod>"
+            + "   </soapenv:Body>" + "</soapenv:Envelope>";
+
+    static final WSSecurityEngine secEngine = new WSSecurityEngine();
+
+    static final Crypto crypto = CryptoFactory
+            .getInstance("cryptoSKI.properties");
+
+    MessageContext msgContext;
+
+    Message message;
+
+    /**
+     * Table of secrets idexd by the sct identifiers
+     */
+    private Hashtable secrets = new Hashtable();
+
+    /**
+     * @param arg0
+     */
+    public TestWSSecurityNewSCT(String arg0) {
+        super(arg0);
+    }
+
+    /**
+     * Setup method <p/>
+     * 
+     * @throws Exception
+     *             Thrown when there is a problem in setup
+     */
+    protected void setUp() throws Exception {
+        AxisClient tmpEngine = new AxisClient(new NullProvider());
+        msgContext = new MessageContext(tmpEngine);
+        message = getSOAPMessage();
+    }
+
+    public void testBuild() {
+        try {
+            SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+            Document doc = unsignedEnvelope.getAsDocument();
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+            sctBuilder.build(doc, crypto, secHeader);
+            sctBuilder.commit(doc, crypto, secHeader);
+
+            String out = org.apache.ws.security.util.XMLUtils
+                    .PrettyDocumentToString(doc);
+
+            assertTrue(
+                    "SecurityContextToken missing",
+                    out
+                            .indexOf(ConversationConstants.SECURITY_CONTEXT_TOKEN_LN) > 0);
+            assertTrue("wsc:Identifier missing", out
+                    .indexOf(ConversationConstants.IDENTIFIER_LN) > 0);
+
+            // System.out.println(out);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail(e.getMessage());
+        }
+    }
+
+    /**
+     * Test encryption using a derived key which is based on a secret associated
+     * with a security context token
+     */
+    public void testSCTDKEncryptDecrypt() {
+        try {
+            SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+            Document doc = unsignedEnvelope.getAsDocument();
+            WSSecHeader secHeader = new WSSecHeader();
+            secHeader.insertSecurityHeader(doc);
+
+            WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
+            sctBuilder.build(doc, crypto, secHeader);
+
+            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+            byte[] tempSecret = new byte[16];
+            random.nextBytes(tempSecret);
+
+            // Store the secret
+            this.secrets.put(sctBuilder.getIdentifier(), tempSecret);
+
+            String tokenId = sctBuilder.getSctId();
+
+            // Derived key encryption
+            WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+            encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+            encrBuilder.setExternalKey(tempSecret, tokenId);
+            encrBuilder.build(doc, crypto, secHeader);
+
+            sctBuilder.commit(doc, crypto, secHeader);
+
+//            String out = org.apache.ws.security.util.XMLUtils
+//                    .PrettyDocumentToString(doc);
+
+//            System.out.println(out);
+            
+            verify(doc);
+        } catch (Exception e) {
+            e.printStackTrace();
+            fail(e.getMessage());
+        }
+    }
+    
+    /**
+     * Verifies the soap envelope
+     * <p/>
+     * 
+     * @param envelope 
+     * @throws Exception Thrown when there is a problem in verification
+     */
+    private void verify(Document doc) throws Exception {
+        secEngine.processSecurityHeader(doc, null, this, crypto);
+        SOAPUtil.updateSOAPMessage(doc, message);
+        String decryptedString = message.getSOAPPartAsString();
+        assertTrue(decryptedString.indexOf("LogTestService2") > 0 ? true : false);
+    }
+
+    /**
+     * Constructs a soap envelope <p/>
+     * 
+     * @return soap envelope
+     * @throws Exception
+     *             if there is any problem constructing the soap envelope
+     */
+    protected Message getSOAPMessage() throws Exception {
+        InputStream in = new ByteArrayInputStream(soapMsg.getBytes());
+        Message msg = new Message(in);
+        msg.setMessageContext(msgContext);
+        return msg;
+    }
+
+    public void handle(Callback[] callbacks) throws IOException,
+            UnsupportedCallbackException {
+        for (int i = 0; i < callbacks.length; i++) {
+            if (callbacks[i] instanceof WSPasswordCallback) {
+                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+                byte[] secret = (byte[]) this.secrets.get(pc.getIdentifer());
+                pc.setKey(secret);
+            } else {
+                throw new UnsupportedCallbackException(callbacks[i],
+                        "Unrecognized Callback");
+            }
+        }
+    }
+
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: wss4j-dev-unsubscribe@ws.apache.org
For additional commands, e-mail: wss4j-dev-help@ws.apache.org