You are viewing a plain text version of this content. The canonical link for it is here.
Posted to fx-dev@ws.apache.org by di...@apache.org on 2004/06/18 13:33:04 UTC

cvs commit: ws-fx/wss4j/src/org/apache/ws/security/message WSEncryptBody.java

dims        2004/06/18 04:33:04

  Modified:    wss4j/src/org/apache/ws/security/message WSEncryptBody.java
  Added:       wss4j/src/org/apache/ws/security/conversation/message/token
                        BaseToken.java DerivedKeyToken.java
                        RequestedProofToken.java
                        RequestedSecurityToken.java
                        RequestSecurityToken.java
                        RequestSecurityTokenResponse.java
                        SecurityContextToken.java
               wss4j/src/org/apache/ws/security/conversation
                        ConversationConstants.java
                        ConversationException.java ConversationManager.java
                        ConversationSession.java ConversationUtil.java
                        DerivedKeyCallbackHandler.java
                        DerivedKeyTokenAdder.java KeyDerivator.java
               wss4j/src/org/apache/ws/security/conversation/message/info
                        DerivedKeyInfo.java SecurityContextInfo.java
               wss4j/src/org/apache/ws/security/trust TrustConstants.java
  Log:
  initial check-in (and 1 patch) for WS-Trust and WS-SecureConversation from the Sri Lanka team.
  
  Revision  Changes    Path
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/BaseToken.java
  
  Index: BaseToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.message.token;
  
  /**
   * Class BaseToken
   */
  public class BaseToken {
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/DerivedKeyToken.java
  
  Index: DerivedKeyToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.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.message.token.SecurityTokenReference;
  import org.apache.ws.security.util.DOM2Writer;
  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.NodeList;
  import org.w3c.dom.Text;
  
  import javax.xml.namespace.QName;
  import java.util.Enumeration;
  import java.util.Hashtable;
  
  /**
   * <DerivedKeyToken wsu:Id="..." wsc:Algorithm="...">
   * <SecurityTokenReference>...</SecurityTokenReference>
   * <Properties>...</Properties>
   * <Generation>...</Generation>
   * <Offset>...</Offset>
   * <Length>...</Length>
   * <Label>...</Label>
   * <Nonce>...</Nonce>
   * </DerivedKeyToken>
   */
  public class DerivedKeyToken {
  
      /**
       * Field TOKEN
       */
      public static final QName TOKEN =
              new QName(ConversationConstants.WSC_NS,
                      ConversationConstants.DERIVED_KEY_TOKEN_LN);
  
      // These are the elements that are used to create the SecurityContextToken
  
      /**
       * Field element
       */
      protected Element element = null;
  
      /**
       * Field elementSecurityTokenReference
       */
      protected Element elementSecurityTokenReference = null;
  
      /**
       * Field elementProperties
       */
      protected Element elementProperties = null;
  
      /**
       * Field elementGeneration
       */
      protected Element elementGeneration = null;
  
      /**
       * Field elementOffset
       */
      protected Element elementOffset = null;
  
      /**
       * Field elementLength
       */
      protected Element elementLength = null;
  
      /**
       * Field elementLabel
       */
      protected Element elementLabel = null;
  
      /**
       * Field elementNonce
       */
      protected Element elementNonce = null;
  
      /**
       * This will create an empty DerivedKeyToken
       * 
       * @param doc THe DOM document
       */
      public DerivedKeyToken(Document doc) {
          this.element =
                  doc.createElementNS(ConversationConstants.WSC_NS,
                          "wsc:"
                  + ConversationConstants.DERIVED_KEY_TOKEN_LN);
          WSSecurityUtil.setNamespace(this.element, ConversationConstants.WSC_NS,
                  WSConstants.WSSE_PREFIX);
      }
  
      /**
       * This will create a DerivedKeyToken object with the given DErivedKeyToken element
       * 
       * @param elem The DErivedKeyToken DOM element
       * @throws WSSecurityException If the element is not a derived key token
       */
      public DerivedKeyToken(Element elem) throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(),
                  this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
                      new Object[]{el});
          }
          this.elementSecurityTokenReference =
                  (Element) WSSecurityUtil.getDirectChild(this.element,
                          ConversationConstants.SECURITY_TOKEN_REFERENCE_LN,
                          WSConstants.WSSE_NS);
          this.elementProperties =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.PROPERTIES_LN,
                          ConversationConstants.WSC_NS);
          this.elementGeneration =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.GENERATION_LN,
                          ConversationConstants.WSC_NS);
          this.elementOffset =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.OFFSET_LN,
                          ConversationConstants.WSC_NS);
          this.elementLength =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.LENGTH_LN,
                          ConversationConstants.WSC_NS);
          this.elementLabel =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.LABEL_LN,
                          ConversationConstants.WSC_NS);
          this.elementNonce =
                  (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.NONCE_LN,
                          ConversationConstants.WSC_NS);
      }
  
      /**
       * Sets the security token reference of the derived key token
       * This is the reference to the shared secret used in the conversation/context
       * 
       * @param doc The DOM document
       * @param ref Security token reference
       */
      public void setSecuityTokenReference(Document doc,
                                           SecurityTokenReference ref) {
          WSSecurityUtil.appendChildElement(doc, this.element, ref.getElement());
      }
  
      /**
       * Returns the SecurityTokenReference of the derived key token
       * 
       * @return 
       * @throws WSSecurityException 
       */
      public SecurityTokenReference getSecuityTokenReference()
              throws WSSecurityException {
          if (this.elementSecurityTokenReference != null) {
              return new SecurityTokenReference(this.elementSecurityTokenReference);
          }
          return null;
      }
  
      // Write the getter for security token reference
  
      /**
       * This adds a property into
       * /DerivedKeyToken/Properties
       * 
       * @param doc       The DOM document
       * @param propName  Name of the property
       * @param propValue Value of the property
       */
      private void addProperty(Document doc, String propName, String propValue) {
          if (this.elementProperties
                  == null) {    // Create the properties element if it is not there
              this.elementProperties =
                      doc.createElementNS(ConversationConstants.WSC_NS,
                              "wsc:"
                      + ConversationConstants.PROPERTIES_LN);
              WSSecurityUtil.setNamespace(this.elementProperties,
                      ConversationConstants.WSC_NS,
                      WSConstants.WSSE_PREFIX);
              this.element.appendChild(this.elementProperties);
          }
          Element tempElement = doc.createElementNS(ConversationConstants.WSC_NS,
                  "wsc:" + propName);
          tempElement.appendChild(doc.createTextNode(propValue));
          this.elementProperties.appendChild(tempElement);
      }
  
      /**
       * This is used to set the Name, Label and Nonce element values in the properties element
       * <b>At this point I'm not sure if these are the only properties that will appear in the
       * <code>Properties</code> element. There fore this method is provided
       * If this is not required feel free to remove this :D
       * </b>
       * 
       * @param doc   The DOM document
       * @param name  Value of the Properties/Name element
       * @param label Value of the Properties/Label element
       * @param nonce Value of the Properties/Nonce element
       */
      public void setProperties(Document doc, String name, String label,
                                String nonce) {
          Hashtable table = new Hashtable(3);
          table.put("Name", name);
          table.put("Label", label);
          table.put("Nonce", nonce);
          this.setProperties(doc, table);
      }
  
      /**
       * If there are other types of properties other than Name, Label and Nonce
       * This is provided for extensibility purposes
       * 
       * @param doc        
       * @param properties The properties and values in a hashtable
       */
      public void setProperties(Document doc, Hashtable properties) {
          Enumeration keys = properties.keys();
          while (keys.hasMoreElements()) {
              String propertyName =
                      (String) keys.nextElement();    // Get the property name
  
              // Check whether this property is already there
              // If so change the value
              Node node =
                      WSSecurityUtil.findElement(this.elementProperties,
                              propertyName,
                              ConversationConstants.WSC_NS);
              if ((node != null)
                      && (node instanceof Element)) {    // If the node is not null
                  Text node1 = getFirstNode((Element) node);
                  node1.setData((String) properties.get(propertyName));
              } else {
                  this.addProperty(doc, propertyName,
                          (String) properties.get(propertyName));
              }
          }
      }
  
      /**
       * Method getProperties
       * 
       * @return 
       */
      public Hashtable getProperties() {
          if (this.elementProperties != null) {
              Hashtable table = new Hashtable();
              NodeList nodes = this.elementProperties.getChildNodes();
              for (int i = 0; i < nodes.getLength(); i++) {
                  Node tempNode = nodes.item(i);
                  if (tempNode instanceof Element) {
                      Text text = this.getFirstNode((Element) tempNode);
                      System.out.println(tempNode.getNodeName() + " : "
                              + text.getData());
                      table.put(tempNode.getNodeName(), text.getData());
                  }
              }
          }
          return null;
      }
  
      /**
       * Sets the length of the derived key
       * 
       * @param doc    The DOM document
       * @param length The length of the derived key as a long
       */
      public void setLength(Document doc, long length) {
          this.elementLength =
                  doc.createElementNS(ConversationConstants.WSC_NS,
                          "wsc:" + ConversationConstants.LENGTH_LN);
          WSSecurityUtil.setNamespace(this.elementLength,
                  ConversationConstants.WSC_NS,
                  WSConstants.WSSE_PREFIX);
          this.elementLength.appendChild(doc.createTextNode(Long.toString(length)));
          this.element.appendChild(this.elementLength);
      }
  
      /**
       * Method getLength
       * 
       * @return 
       */
      public long getLength() {
          if (this.elementLength != null) {
              return Long.parseLong(getFirstNode(this.elementLength).getData());
          }
          return -1;
      }
  
      /**
       * Sets the offset
       * 
       * @param doc    The DOM document
       * @param offset The offset value as an integer
       */
      public void setOffset(Document doc, int offset) {
          // This element MUST NOT be used if the <Generation> element is specified
          if (this.elementGeneration == null) {
              this.elementOffset =
                      doc.createElementNS(ConversationConstants.WSC_NS,
                              "wsc:" + ConversationConstants.OFFSET_LN);
              WSSecurityUtil.setNamespace(this.elementOffset,
                      ConversationConstants.WSC_NS,
                      WSConstants.WSSE_PREFIX);
              this.elementOffset.appendChild(doc.createTextNode(Integer.toString(offset)));
              this.element.appendChild(this.elementOffset);
          }
      }
  
      /**
       * Method getOffset
       * 
       * @return 
       */
      public int getOffset() {
          if (this.elementOffset != null) {
              return Integer.parseInt(getFirstNode(this.elementOffset).getData());
          }
          return -1;
      }
  
      /**
       * Sets the generation of the derived key
       * 
       * @param doc        The DOM document
       * @param generation generation value as an integer
       */
      public void setGeneration(Document doc, int generation) {
          // This element MUST NOT be used if the <Offset> element is specified
          if (this.elementOffset == null) {
              this.elementGeneration =
                      doc.createElementNS(ConversationConstants.WSC_NS,
                              "wsc:"
                      + ConversationConstants.GENERATION_LN);
              WSSecurityUtil.setNamespace(this.elementGeneration,
                      ConversationConstants.WSC_NS,
                      WSConstants.WSSE_PREFIX);
              this.elementGeneration.appendChild(doc.createTextNode(Integer.toString(generation)));
              this.element.appendChild(this.elementGeneration);
          } else {
              /** @todo set the value of the existing element */
          }
      }
  
      /**
       * Method getGeneration
       * 
       * @return 
       */
      public int getGeneration() {
          if (this.elementGeneration != null) {
              return Integer.parseInt(getFirstNode(this.elementGeneration).getData());
          }
          return -1;
      }
  
      /**
       * Sets the label of the derived key
       * 
       * @param doc   The DOM document
       * @param label Label value as a string
       */
      public void setLabel(Document doc, String label) {
          this.elementLabel =
                  doc.createElementNS(ConversationConstants.WSC_NS,
                          "wsc:" + ConversationConstants.LABEL_LN);
          WSSecurityUtil.setNamespace(this.elementLabel,
                  ConversationConstants.WSC_NS,
                  WSConstants.WSSE_PREFIX);
          this.elementLabel.appendChild(doc.createTextNode(label));
          this.element.appendChild(this.elementLabel);
      }
  
      /**
       * Sets the nonce value of the derived key
       * 
       * @param doc   The DOM document
       * @param nonce Nonce value as a string
       */
      public void setNonce(Document doc, String nonce) {
          this.elementNonce =
                  doc.createElementNS(ConversationConstants.WSC_NS,
                          "wsc:" + ConversationConstants.NONCE_LN);
          WSSecurityUtil.setNamespace(this.elementNonce,
                  ConversationConstants.WSC_NS,
                  WSConstants.WSSE_PREFIX);
          this.elementNonce.appendChild(doc.createTextNode(nonce));
          this.element.appendChild(this.elementNonce);
      }
  
      /**
       * Returns the label of the derived key token
       * 
       * @return Label of the derived key token
       */
      public String getLabel() {
          if (this.elementLabel != null) {
              return getFirstNode(this.elementLabel).getData();
          }
          return null;
      }
  
      /**
       * Return the nonce of the derived key token
       * 
       * @return Nonce of the derived key token
       */
      public String getNonce() {
          if (this.elementNonce != null) {
              return getFirstNode(this.elementNonce).getData();
          }
          return null;
      }
  
      /**
       * 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 DerivedKeyToken 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 username 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);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestedProofToken.java
  
  Index: RequestedProofToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.message.token;
  
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityEngine;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.components.crypto.Crypto;
  import org.apache.ws.security.components.crypto.CryptoFactory;
  import org.apache.ws.security.message.WSEncryptBody;
  import org.apache.ws.security.util.DOM2Writer;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  
  import javax.security.auth.callback.CallbackHandler;
  import javax.xml.namespace.QName;
  
  /**
   * Class RequestedProofToken
   */
  public class RequestedProofToken {
  
      /**
       * Field log
       */
      private static Log log =
              LogFactory.getLog(RequestedProofToken.class.getName());
  
      /**
       * Field TOKEN
       */
      public static final QName TOKEN = new QName(WSConstants.WSSE_NS,
              "RequestedProofToken");
  
      /**
       * Field proofEle
       */
      private Element proofEle;
  
      /**
       * Field keyInfoEle
       */
      private Element keyInfoEle;
  
      /**
       * Field mgmtDataEle
       */
      private Element mgmtDataEle;
  
      /**
       * Field sharedSecret
       */
      private byte[] sharedSecret = null;
  
      // TODO :: Change this .............
  
      /**
       * Field encCrypto
       */
      private Crypto encCrypto = null;
  
      /**
       * Field doDebug
       */
      private boolean doDebug = false;
  
      /**
       * Field base
       */
      private BaseToken base;
  
      /**
       * Field symEncAlgo
       */
      protected String symEncAlgo = WSConstants.TRIPLE_DES;
  
      /**
       * Field keyEncAlgo
       */
      protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
  
      /*
       * The RequestedProofToken look like this.
       *
       *  <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/04/xmldsig#' >
       *    <ds:MgmtData>i3jTGW6PnDuf4ax603i20A==</ds:MgmtData>
       *   </ds:KeyInfo>
       */
  
      /**
       * Constructor.
       * 
       * @param doc    is the SOAP envelop.
       * @param secret is the secret.
       * @throws WSSecurityException 
       */
      public RequestedProofToken(Document doc) throws WSSecurityException {
          this.proofEle = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:RequestedProofToken");
          System.out.println("RequestedProofToken....... created .....");
      }
  
      /**
       * COnstructor
       * 
       * @param elem 
       * @throws WSSecurityException 
       */
      public RequestedProofToken(Element elem) throws WSSecurityException {
          doDebug = log.isDebugEnabled();
          QName el = new QName(elem.getNamespaceURI(), elem.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.FAILURE,
                      "badElement", new Object[]{TOKEN,
                                                 el});
          }
          this.proofEle = elem;
      }
  
      /**
       * Method doDecryption
       * 
       * @param callback 
       * @param crypto   
       * @throws WSSecurityException 
       */
      public void doDecryption(String callback, Crypto crypto)
              throws WSSecurityException {
          WSSecurityEngine secEngine = new WSSecurityEngine();
          CallbackHandler cbHandler;
  
          // Element
          NodeList ndList = this.proofEle.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey");
          if (ndList.getLength() < 1) {
              throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                      "RequestedProofToken is empty");
          }
  
          // CbHandler :: taken from WSSecurityEngine class
          if (callback != null) {
              Class cbClass = null;
              try {
                  cbClass = java.lang.Class.forName(callback);
              } catch (ClassNotFoundException e) {
                  throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
                          "RequestedProofToken: cannot load password callback class: "
                          + callback);
              }
              try {
                  cbHandler = (CallbackHandler) cbClass.newInstance();
              } catch (java.lang.Exception e) {
                  throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
                          "RequestedProofToken: cannot create instance of password callback: "
                          + callback);
              }
              secEngine.handleEncryptedKey((Element) ndList.item(0), cbHandler,
                      crypto);
  
              // this.sharedSecret=secEngine.getDecryptedBytes();
              System.out.println(new String(this.sharedSecret));
          } else {
              System.out.println("Do somehting....... Decryption problem");
          }
      }
  
      /**
       * Method doEncryptProof
       * 
       * @param doc 
       */
      public void doEncryptProof(Document doc) {
          // throws WSSecurityException {
          WSEncryptBody wsEncrypt = new WSEncryptBody();
  
          // try {
          Crypto crypto;
          crypto = CryptoFactory.getInstance("crypto.properties");
          wsEncrypt.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
          wsEncrypt.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
  
          // wsEncrypt.setParentNode(
          // (Element) (doc
          // .getElementsByTagNameNS(
          // WSConstants.WSSE_NS,
          // "RequestedProofToken")
          // .item(0)));
          // wsEncrypt.build(doc, crypto);
          // // this.sharedSecret=wsEncrypt.getSymmetricKey().getEncoded();
          // System.out.println(new String(sharedSecret));
          // } catch (WSSecurityException e) {
          // e.printStackTrace();
          // }
      }
  
      /**
       * Method getElement
       * 
       * @return 
       */
      public Element getElement() {
          return this.proofEle;
      }
  
      /**
       * @return 
       */
      public byte[] getSharedSecret() {
          return sharedSecret;
      }
  
      /**
       * Method getID
       * 
       * @return 
       */
      public String getID() {
          return this.proofEle.getAttributeNS(WSConstants.WSU_NS, "Id");
      }
  
      /**
       * Method toString
       * 
       * @return 
       */
      public String toString() {
          return DOM2Writer.nodeToString((Node) this.proofEle);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestedSecurityToken.java
  
  Index: RequestedSecurityToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.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.trust.TrustConstants;
  import org.apache.ws.security.util.DOM2Writer;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  
  import javax.xml.namespace.QName;
  
  /**
   * Class RequestedSecurityToken
   */
  public class RequestedSecurityToken {
  
      /**
       * Field securityContextToken
       */
      private SecurityContextToken securityContextToken;
  
      /**
       * Field element
       */
      private Element element = null;
  
      /**
       * Field TOKEN
       */
      public static final QName TOKEN =
              new QName(WSConstants.WSSE_NS,
                      TrustConstants.REQUESTED_SECURITY_TOKEN_LN);
  
      /**
       * Constructor
       * 
       * @param doc                  
       * @param securityContextToken 
       * @throws Exception 
       */
      public RequestedSecurityToken(Document doc, SecurityContextToken securityContextToken)
              throws Exception {
          this.securityContextToken = securityContextToken;
          this.element = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + TrustConstants.REQUESTED_SECURITY_TOKEN_LN);
          this.securityContextToken = securityContextToken;
          this.element.appendChild(securityContextToken.getElement());
      }
  
      /**
       * To create a RequestSecurityTokenResponse token form an element passed
       * 
       * @param elem 
       * @throws WSSecurityException 
       */
      public RequestedSecurityToken(Element elem) throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(),
                  this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
                      new Object[]{el});
          }
          Element token = (Element) WSSecurityUtil.getDirectChild(element,
                  ConversationConstants.SECURITY_CONTEXT_TOKEN_LN,
                  WSConstants.WSSE_NS);
          securityContextToken = new SecurityContextToken(token);
  
          // ??? Discuss what elements are optional and wht are not
      }
  
      /**
       * Method toString
       * 
       * @return 
       */
      public String toString() {
          return DOM2Writer.nodeToString((Node) this.element);
      }
  
      /**
       * @return 
       */
      public Element getElement() {
          return element;
      }
  
      /**
       * Method setElement
       * 
       * @param element 
       */
      public void setElement(Element element) {
          this.element = element;
      }
  
      /**
       * Method getSecurityContextToken
       * 
       * @return 
       */
      public SecurityContextToken getSecurityContextToken() {
          return securityContextToken;
      }
  
      /**
       * Method setSecurityContextToken
       * 
       * @param securityContextToken 
       */
      public void setSecurityContextToken(SecurityContextToken securityContextToken) {
          this.securityContextToken = securityContextToken;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestSecurityToken.java
  
  Index: RequestSecurityToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.message.token;
  
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.trust.TrustConstants;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import javax.xml.soap.SOAPElement;
  import javax.xml.soap.SOAPMessage;
  
  /**
   * Class RequestSecurityToken
   */
  public class RequestSecurityToken {
  
      /**
       * Field message
       */
      private SOAPMessage message;
  
      /**
       * Field reqType
       */
      private String reqType;
  
      /**
       * Field tokenType
       */
      private String tokenType;
  
      /**
       * Field doc
       */
      private Document doc;
  
      /**
       * Field token
       */
      private Element token;
  
      /**
       * Constructor RequestSecurityToken
       * 
       * @param element 
       * @throws WSSecurityException 
       */
      public RequestSecurityToken(Element element) throws WSSecurityException {
          // TODO :: Support only for SCT - for now
          token = (Element) WSSecurityUtil.getDirectChild(element,
                  TrustConstants.SECURITY_CONTEXT_TOKEN_LN, WSConstants.WSSE_NS);
          SecurityContextToken sct = new SecurityContextToken(token);
      }
  
      /**
       * Constructor RequestSecurityToken
       * 
       * @param message   
       * @param tokenType 
       * @param reqType   
       * @throws Exception 
       */
      public RequestSecurityToken(SOAPMessage message, String tokenType, String reqType)
              throws Exception {
          this.message = message;
          this.tokenType = tokenType;
          this.reqType = reqType;
          this.processDocuement();
      }
  
      /**
       * Method processDocuement
       * 
       * @throws Exception 
       */
      private void processDocuement() throws Exception {
          // SOAPElement reqSecToken = this.message.getSOAPPart().getEnvelope().getBody().addChildElement("RequestSecurityToken");
          this.message.getSOAPPart().getEnvelope().getBody().detachNode();
          SOAPElement reqSecToken =
                  this.message.getSOAPPart().getEnvelope().addBody().addChildElement("RequestSecurityToken");
          System.out.println("Body : "
                  + this.message.getSOAPPart().getEnvelope().getBody().toString());
  
          // Creating the TokenType element
          SOAPElement tokenTypeElement = reqSecToken.addChildElement("TokenType");
          tokenTypeElement.addTextNode(this.tokenType);
  
          // Creating the RequestType element
          SOAPElement requestTypeElement =
                  reqSecToken.addChildElement("RequestType");
          requestTypeElement.addTextNode(this.reqType);
          System.out.println("My Body : " + this.message.getSOAPPart().getEnvelope().getBody());
      }
  
      // public RequestSecurityToken(Document doc,String tokenType, String reqType) throws Exception{
      // this.doc = doc;
      // this.tokenType = tokenType;
      // this.reqType = reqType;
      // this.processDocuement();
      // }
      // 
      // private void processDocuement() throws Exception{
      // SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
      // Element bodyElement =
      // (Element) WSSecurityUtil.getDirectChild(
      // doc.getFirstChild(),
      // soapConstants.getBodyQName().getLocalPart(),
      // soapConstants.getEnvelopeURI());
      // if (bodyElement == null) {
      // throw new Exception("SOAP Body Element node not found");
      // }
      // 
      // Element reqSecToken = doc.createElement("RequestSecurityToken");
      // 
      // //Creating the TokenType element
      // Element tokenTypeElement = doc.createElement("TokenType");
      // tokenTypeElement.appendChild(doc.createTextNode(this.tokenType));
      // 
      // //Creating the RequestType element
      // Element requestTypeElement = doc.createElement("RequestType");
      // requestTypeElement.appendChild(doc.createTextNode(this.reqType));
      // 
      // //Adding the elements into RequestSecurityToken element
      // reqSecToken.appendChild(tokenTypeElement);
      // reqSecToken.appendChild(requestTypeElement);
      // 
      // }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestSecurityTokenResponse.java
  
  Index: RequestSecurityTokenResponse.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.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.message.WSBaseMessage;
  import org.apache.ws.security.trust.TrustConstants;
  import org.apache.ws.security.util.DOM2Writer;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.apache.xml.security.keys.KeyInfo;
  import org.apache.xml.security.utils.XMLUtils;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  
  import javax.xml.namespace.QName;
  import java.io.ByteArrayOutputStream;
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.TimeZone;
  
  /**
   * Class RequestSecurityTokenResponse
   */
  public class RequestSecurityTokenResponse extends WSBaseMessage {
  
      /**
       * Field element
       */
      private Element element = null;
  
      /**
       * Field tokenTypeEle
       */
      private Element tokenTypeEle;
  
      /**
       * Field keyTypeEle
       */
      private Element keyTypeEle;
  
      /**
       * Field keySizeEle
       */
      private Element keySizeEle;
  
      /**
       * Field LifeTime
       */
      private Element LifeTime = null;
  
      /**
       * Field Created
       */
      private Element Created = null;
  
      /**
       * Field Expires
       */
      private Element Expires = null;
  
      /**
       * Field tokenType
       */
      private String tokenType;
  
      /**
       * Field keyType
       */
      private String keyType;
  
      /**
       * Field keySize
       */
      private String keySize;
  
      /**
       * Field requestedProofToken
       */
      private RequestedProofToken requestedProofToken;
  
      /**
       * Field requestedSecurityToken
       */
      private RequestedSecurityToken requestedSecurityToken;
  
      /**
       * Field keyInfo
       */
      private KeyInfo keyInfo;
  
      /**
       * Field TOKEN
       */
      public static final QName TOKEN =
              new QName(WSConstants.WSSE_NS,
                      TrustConstants.SECURITY_CONTEXT_TOKEN_RESPONSE_LN);
  
      /**
       * Constructor
       * 
       * @param doc 
       * @throws java.lang.Exception 
       * @throws Exception           
       */
      public RequestSecurityTokenResponse(Document doc) throws Exception {
          this.element = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + TrustConstants.SECURITY_CONTEXT_TOKEN_RESPONSE_LN);
          this.tokenTypeEle = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:"
                  + TrustConstants.TOKEN_TYPE_LN);
          this.keyTypeEle = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:"
                  + TrustConstants.KEY_TYPE_LN);
  
          /*
           * WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS,
           *                           WSConstants.WSSE_PREFIX);
           * WSSecurityUtil.setNamespace(this.tokenTypeEle, WSConstants.WSSE_NS,
           *                           WSConstants.WSSE_PREFIX);
           * WSSecurityUtil.setNamespace(this.keyTypeEle, WSConstants.WSSE_NS,
           *                           WSConstants.WSSE_PREFIX);
           */
          this.keySizeEle = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:"
                  + TrustConstants.KEY_SIZE_LN);
          WSSecurityUtil.setNamespace(this.keySizeEle, WSConstants.WSSE_NS,
                  WSConstants.WSSE_PREFIX);
          this.tokenTypeEle.appendChild(doc.createTextNode(""));
          this.keyTypeEle.appendChild(doc.createTextNode(""));
          this.keySizeEle.appendChild(doc.createTextNode(""));
          SecurityContextToken cntxtToken = new SecurityContextToken(doc);
          this.requestedSecurityToken = new RequestedSecurityToken(doc,
                  cntxtToken);
  
          /*
           * elements are added without any logic.???
           */
          this.element.appendChild(this.tokenTypeEle);
          this.element.appendChild(this.keyTypeEle);
          this.element.appendChild(this.keySizeEle);
          this.element.appendChild(this.createLifeTimeElement(doc));
          this.element.appendChild(requestedSecurityToken.getElement());    // ruchith
          this.element.appendChild(this.createRequestedProofToken(doc));    // dimuthu
      }
  
      /**
       * To create a RequestSecurityTokenResponse token form an element passed
       * 
       * @param elem 
       * @throws WSSecurityException 
       */
      public RequestSecurityTokenResponse(Element elem)
              throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(),
                  this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
                      new Object[]{el});
          }
          tokenTypeEle = (Element) WSSecurityUtil.getDirectChild(element,
                  TrustConstants.TOKEN_TYPE_LN, WSConstants.WSSE_NS);
          keyTypeEle = (Element) WSSecurityUtil.getDirectChild(element,
                  TrustConstants.KEY_TYPE_LN, WSConstants.WSSE_NS);
          keySizeEle = (Element) WSSecurityUtil.getDirectChild(element,
                  TrustConstants.KEY_SIZE_LN, WSConstants.WSSE_NS);
          LifeTime = (Element) WSSecurityUtil.getDirectChild(element,
                  TrustConstants.LIFE_TIME_LN, WSConstants.WSU_NS);
          Created = (Element) WSSecurityUtil.getDirectChild(element,
                  WSConstants.CREATED_LN, WSConstants.WSSE_NS);
          Expires = (Element) WSSecurityUtil.getDirectChild(element,
                  ConversationConstants.EXPIRES_LN, WSConstants.WSU_NS);
  
          // ??? Discuss what elements are optional and wht are not
          this.requestedSecurityToken = new RequestedSecurityToken((Element) WSSecurityUtil.getDirectChild(element, TrustConstants.REQUESTED_SECURITY_TOKEN_LN,
                  WSConstants.WSSE_NS));
          this.requestedProofToken = new RequestedProofToken((Element) WSSecurityUtil.getDirectChild(element, "RequestedProofToken", WSConstants.WSSE_NS));
      }
  
      /**
       * @param doc 
       * @return 
       * @throws WSSecurityException 
       */
      private Element createRequestedProofToken(Document doc)
              throws WSSecurityException {
          this.requestedProofToken = new RequestedProofToken(doc);
          return this.requestedProofToken.getElement();
      }
  
      /**
       * Set requested security token
       * 
       * @param requestedSecurityToken 
       */
      public void setRequestedSecurityToken(RequestedSecurityToken requestedSecurityToken) {
          this.requestedSecurityToken = requestedSecurityToken;
      }
  
      /**
       * set Requested ProofToken
       * 
       * @param requestedProofToken 
       */
      public void setRequestedProofToken(RequestedProofToken requestedProofToken) {
          this.requestedProofToken = requestedProofToken;
      }
  
      /**
       * @return 
       */
      public String toString() {
          return DOM2Writer.nodeToString((Node) this.element);
      }
  
      /**
       * Sets the lifetime element refer SAML document
       * 
       * @param doc 
       * @return 
       */
      private Element createLifeTimeElement(Document doc) {
          SimpleDateFormat sdtf =
                  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
          sdtf.setTimeZone(TimeZone.getTimeZone("GMT"));
          Calendar rightNow = Calendar.getInstance();
          this.LifeTime = doc.createElementNS(WSConstants.WSU_NS,
                  "wsu:"
                  + TrustConstants.LIFE_TIME_LN);
          WSSecurityUtil.setNamespace(this.LifeTime, WSConstants.WSU_NS,
                  WSConstants.WSU_PREFIX);
          this.Created = doc.createElementNS(WSConstants.WSU_NS,
                  "wsu:" + WSConstants.CREATED_LN);
          WSSecurityUtil.setNamespace(this.Created, WSConstants.WSU_NS,
                  WSConstants.WSU_PREFIX);
          this.Expires = doc.createElementNS(WSConstants.WSU_NS,
                  "wsu:"
                  + ConversationConstants.EXPIRES_LN);
          this.Created.appendChild(doc.createTextNode(sdtf.format(rightNow.getTime())));
          this.Expires.appendChild(doc.createTextNode(sdtf.format(rightNow.getTime())));    // Increment by 12 hrs ???
          this.LifeTime.appendChild(Created);
          this.LifeTime.appendChild(Expires);
          return this.LifeTime;
  
          /*
           * String expTimeZone = "GMT+" + this.timeout + ":00";
           *  sdtf.setTimeZone(TimeZone.getTimeZone(expTimeZone));
           *  this.elementExpires.appendChild(doc.createTextNode(sdtf.format(rightNow.getTime())));
           *  element.appendChild(elementExpires);
           */
      }
  
      /**
       * Method getRequestedProfToken
       * 
       * @return 
       */
      public RequestedProofToken getRequestedProfToken() {
          return requestedProofToken;
      }
  
      /**
       * Method getRequestedProofToken
       * 
       * @return 
       */
      public RequestedProofToken getRequestedProofToken() {
          return requestedProofToken;
      }
  
      /**
       * Method getRequestedSecurityToken
       * 
       * @return 
       */
      public RequestedSecurityToken getRequestedSecurityToken() {
          return requestedSecurityToken;
      }
  
      /**
       * Method getElement
       * 
       * @return 
       */
      public Element getElement() {
          return element;
      }
  
      /**
       * Method setElement
       * 
       * @param element 
       */
      public void setElement(Element element) {
          this.element = element;
      }
  
      // added by Dimuthu
  
      /**
       * Method build
       * 
       * @param doc 
       */
      public void build(Document doc) {
          Element securityHeader = insertSecurityHeader(doc);
          WSSecurityUtil.appendChildElement(doc, securityHeader, this.element);
          WSSecurityUtil.setNamespace(securityHeader, WSConstants.WSU_NS,
                  WSConstants.WSU_PREFIX);
  
          // TODO :: Remove this.........
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLUtils.outputDOM(doc, os, true);
          String osStr = os.toString();
          System.out.println(osStr);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/SecurityContextToken.java
  
  Index: SecurityContextToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.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.message.token.SecurityTokenReference;
  import org.apache.ws.security.util.DOM2Writer;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.apache.xml.security.encryption.EncryptedKey;
  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;
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.TimeZone;
  
  /**
   * Class SecurityContextToken
   */
  public class SecurityContextToken {
  
      /**
       * Field TOKEN
       */
      public static final QName TOKEN =
              new QName(WSConstants.WSSE_NS,
                      ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
  
      // These are the elements that are used to create the SecurityContextToken
  
      /**
       * Field element
       */
      protected Element element = null;
  
      /**
       * Field elementIdentifier
       */
      protected Element elementIdentifier = null;
  
      /**
       * Field elementCreated
       */
      protected Element elementCreated = null;
  
      /**
       * Field elementExpires
       */
      protected Element elementExpires = null;
  
      /**
       * Field elementKeys
       */
      protected Element elementKeys = null;
  
      /**
       * Field elementEncryptedKey
       */
      protected Element elementEncryptedKey = null;
  
      /**
       * Field elementSecurityTokenReference
       */
      protected Element elementSecurityTokenReference = null;
  
      /**
       * The time difference between the created time and the expiration time
       */
      protected int timeout = 12;
  
      /**
       * This constructor creates a security context token and adds the identifier
       * 
       * @param doc The DOM Document
       */
      public SecurityContextToken(Document doc) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
          WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS,
                  WSConstants.WSSE_PREFIX);
          this.addIdentifier(doc);    // SEt the uuid
          if (elementCreated == null) {
              addCreatedAndExpires(doc);
          }
      }
  
      /**
       * Constructor to create the SCT given the identifier.
       * 
       * @param doc        
       * @param identifier 
       */
      public SecurityContextToken(Document doc, String identifier) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
          WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS,
                  WSConstants.WSSE_PREFIX);
          this.elementIdentifier = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + ConversationConstants.IDENTIFIER_LN);
          this.element.appendChild(this.elementIdentifier);
          this.elementIdentifier.appendChild(doc.createTextNode(identifier));
      }
  
      /**
       * Constructor to set a custom timeout
       * 
       * @param doc     The DOM Document
       * @param timeout Difference between the creating time and expiration time
       */
      public SecurityContextToken(Document doc, int timeout) {
          // Call to overloaded constructor must vbe the first line
          // But here the timeout has to be set earlier as it is used in addCreatedAndExpires();
          this.element = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
          WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS,
                  WSConstants.WSSE_PREFIX);
          this.addIdentifier(doc);    // Set the uuid
          this.setTimeout(timeout);    // Change the default value of timeout to the given value
          if (elementCreated == null) {
              addCreatedAndExpires(doc);
          }
      }
  
      /**
       * This will generate the Identifier element and generate and set the uuid.s
       * <b>The generation of the UUID is NOT coded </b>
       * 
       * @param doc The DOM Document
       */
      private void addIdentifier(Document doc) {
          this.elementIdentifier = doc.createElementNS(WSConstants.WSSE_NS,
                  "wsse:" + ConversationConstants.IDENTIFIER_LN);
          WSSecurityUtil.setNamespace(this.elementIdentifier,
                  WSConstants.WSSE_NS,
                  WSConstants.WSSE_PREFIX);
          String uuid;
  
          // Creation of the uuid :START
  
          /** @todo */
          uuid = "uuid:secureZone";
  
          // Creation of the uuid :END
          this.elementIdentifier.appendChild(doc.createTextNode(uuid));
          element.appendChild(elementIdentifier);
      }
  
      /**
       * 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, WSConstants.WSSE_NS);
          this.elementCreated =
                  (Element) WSSecurityUtil.getDirectChild(element,
                          WSConstants.CREATED_LN,
                          WSConstants.WSU_NS);
          this.elementExpires =
                  (Element) WSSecurityUtil.getDirectChild(element,
                          WSConstants.EXPIRES_LN,
                          WSConstants.WSU_NS);
  
          // this.elementKeys = (Element) WSSecurityUtil.getDirectChild(element,
          // ConversationConstants.KEYS_LN, WSConstants.WSSE_NS);
          // this.elementEncryptedKey = (Element) WSSecurityUtil.getDirectChild(
          // elementKeys, WSConstants.ENC_KEY_LN, WSConstants.WSSE_NS);
          // this.elementSecurityTokenReference = (Element) WSSecurityUtil.
          // getDirectChild(elementKeys, "SecurityTokenReference",
          // WSConstants.WSSE_NS);
          System.out.println("*\n*\n**\n*\n*\n*\n*\n*****");
  
          // if (this.elementIdentifier == null) {
          // There can't be an SCT without an identifier
          // we still don't have pur own exception class with the properset of error states
          // therefore WSSecurityException is trown
          // throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN,
          // "badTokenType01", new Object[] {el});
          // }
      }
  
      /**
       * This sets the time difference between the created time and the expiration
       * time in hours
       * The default value is 12 hours
       * 
       * @param timeout the number of hours
       */
      private void setTimeout(int timeout) {
          this.timeout = timeout;
      }
  
      /**
       * Returns the timeout value
       * This is the difference between the created time and the expired time
       * 
       * @return The timeout in hours
       */
      public int getTimeout() {
          return this.timeout;
      }
  
      /**
       * Set the identifier.
       * 
       * @param name sets a text node containing the identifier into
       *             the identifier element.
       * @param doc  
       * @param uuid 
       */
      public void setIdentifier(Document doc, String uuid) {
          Text node = getFirstNode(this.elementIdentifier);
          node.setData(uuid);
      }
  
      /**
       * Creates and adds a Created element to this UsernameToken
       * 
       * @param doc The DOM Document
       */
      public void addCreatedAndExpires(Document doc) {
          SimpleDateFormat zulu =
                  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
          zulu.setTimeZone(TimeZone.getTimeZone("GMT"));
          Calendar rightNow = Calendar.getInstance();
          this.elementCreated = doc.createElementNS(WSConstants.WSU_NS,
                  "wsu:"
                  + WSConstants.CREATED_LN);
          WSSecurityUtil.setNamespace(this.elementCreated, WSConstants.WSU_NS,
                  WSConstants.WSU_PREFIX);
          this.elementExpires =
                  doc.createElementNS(WSConstants.WSU_NS,
                          "wsu:" + ConversationConstants.EXPIRES_LN);
          WSSecurityUtil.setNamespace(this.elementCreated, WSConstants.WSU_NS,
                  WSConstants.WSU_PREFIX);
          this.elementCreated.appendChild(doc.createTextNode(zulu.format(rightNow.getTime())));
          element.appendChild(elementCreated);
          String expTimeZone = "GMT+" + this.timeout
                  + ":00";    // The expiration time
          zulu.setTimeZone(TimeZone.getTimeZone(expTimeZone));
          this.elementExpires.appendChild(doc.createTextNode(zulu.format(rightNow.getTime())));
          element.appendChild(elementExpires);
      }
  
      /**
       * Set the encrypted key.
       * 
       * @param doc          
       * @param encryptedKey 
       */
      public void setEncryptedKey(Document doc, EncryptedKey encryptedKey) {
          // If there is no keys element then create it
          if (this.elementKeys == null) {
              this.elementKeys = doc.createElementNS(WSConstants.WSSE_NS,
                      "wsse:Keys");
              this.element.appendChild(this.elementKeys);
          }
  
          /** @todo : Still not sure how to do this */
      }
  
      /**
       * Method setSecuityTokenReference
       * 
       * @param doc 
       * @param ref 
       */
      public void setSecuityTokenReference(Document doc,
                                           SecurityTokenReference ref) {
          // If there is no keys element then create it
          if (this.elementKeys == null) {
              this.elementKeys =
                      doc.createElementNS(WSConstants.WSSE_NS,
                              "wsse:" + ConversationConstants.KEYS_LN);
              WSSecurityUtil.setNamespace(this.elementKeys, WSConstants.WSSE_NS,
                      WSConstants.WSSE_PREFIX);
              this.element.appendChild(this.elementKeys);
          }
          WSSecurityUtil.appendChildElement(doc, this.elementKeys,
                  ref.getElement());
      }
  
      /**
       * Get the created timestamp.
       * 
       * @return the data from the created time element.
       */
      public String getCreated() {
          if (this.elementCreated != null) {
              return getFirstNode(this.elementCreated).getData();
          }
          return null;
      }
  
      /**
       * Get the identifier.
       * 
       * @return the data from the identifier element.
       */
      public String getIdentifier() {
          if (this.elementIdentifier != null) {
              return getFirstNode(this.elementIdentifier).getData();
          }
          return null;
      }
  
      /**
       * Get the expiration timestamp.
       * 
       * @return the data from the created time element.
       */
      public String getExpires() {
          if (this.elementExpires != null) {
              System.out.println("Date is ..............:: "
                      + this.elementExpires.getChildNodes().item(0).getNodeValue());
              return this.elementExpires.getChildNodes().item(0).getNodeValue();
          }
          return null;
      }
  
      /**
       * Set the created timestamp.
       * 
       * @param created sets a text node containing the created time data into
       *                the created time element.
       */
      public void setCreated(String created) {
          Text node = getFirstNode(this.elementCreated);
          node.setData(created);
      }
  
      /**
       * 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 username 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);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationConstants.java
  
  Index: ConversationConstants.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  /**
   * Class ConversationConstants
   */
  public class ConversationConstants {
  
      /**
       * Field WSC_NS
       */
      public final static String WSC_NS =
              "http://schemas.xmlsoap.org/ws/2004/04/sc";
  
      /**
       * Field WSC_PREFIX
       */
      public final static String WSC_PREFIX = "wsc";
  
      /**
       * Field SECURITY_CONTEXT_TOKEN_LN
       */
      public static final String SECURITY_CONTEXT_TOKEN_LN =
              "SecurityContextToken";
  
      /**
       * Field IDENTIFIER_LN
       */
      public static final String IDENTIFIER_LN = "Identifier";
  
      /**
       * Field EXPIRES_LN
       */
      public static final String EXPIRES_LN = "Expires";
  
      /**
       * Field KEYS_LN
       */
      public static final String KEYS_LN = "Keys";
  
      /**
       * Field SECURITY_TOKEN_REFERENCE_LN
       */
      public static final String SECURITY_TOKEN_REFERENCE_LN =
              "SecurityTokenReference";
  
      /**
       * Field DERIVED_KEY_TOKEN_LN
       */
      public static final String DERIVED_KEY_TOKEN_LN = "DerivedKeyToken";
  
      /**
       * Field PROPERTIES_LN
       */
      public static final String PROPERTIES_LN = "Properties";
  
      /**
       * Field LENGTH_LN
       */
      public static final String LENGTH_LN = "Length";
  
      /**
       * Field GENERATION_LN
       */
      public static final String GENERATION_LN = "Generation";
  
      /**
       * Field OFFSET_LN
       */
      public static final String OFFSET_LN = "Offset";
  
      /**
       * Field LABEL_LN
       */
      public static final String LABEL_LN = "Label";
  
      /**
       * Field NONCE_LN
       */
      public static final String NONCE_LN = "Nonce";
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationException.java
  
  Index: ConversationException.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  /**
   * @todo Rewrite this to the way WSSecurityException work or some other proper way
   */
  public class ConversationException extends Exception {
  
      /**
       * Constructor ConversationException
       * 
       * @param message 
       */
      public ConversationException(String message) {
          super(message);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationManager.java
  
  Index: ConversationManager.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.conversation.message.info.DerivedKeyInfo;
  import org.apache.ws.security.conversation.message.token.DerivedKeyToken;
  import org.w3c.dom.Document;
  
  /**
   * This class helps handlers to carry on conversation. Actually the class is the
   * collection of set of methods that are common to both serside and client side
   * handlers.
   */
  public class ConversationManager {
  
      /**
       * Adds Derived key tokens to the header of the SOAP message, given the
       * following parameters.
       * 
       * @param doc         
       * @param uuid        
       * @param dkcbHandler 
       * @param genID       
       * @throws WSSecurityException   
       * @throws ConversationException 
       */
      public void addDerivedKeyToken(Document doc, String uuid, DerivedKeyCallbackHandler dkcbHandler, String genID)
              throws WSSecurityException, ConversationException {
          // Derrive the token
          DerivedKeyToken dtoken = new DerivedKeyToken(doc);
          dtoken.setLabel(doc, "WSSecureConversationWSSecureConversation");
          genID = ConversationUtil.genericID();
          dtoken.setNonce(doc, "nonce.....");
          dtoken.setID(genID);
  
          // add the derived key token into the dkcbHandler
          String identifier = ConversationUtil.generateIdentifier(uuid,
                  genID);
          DerivedKeyInfo dkInfo = new DerivedKeyInfo(dtoken);
          dkcbHandler.addDerivedKey(identifier, dkInfo);
  
          // add the token to the soap message
          DerivedKeyTokenAdder adder = new DerivedKeyTokenAdder();
          adder.build(doc, dtoken);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationSession.java
  
  Index: ConversationSession.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import org.apache.ws.security.conversation.message.info.DerivedKeyInfo;
  import org.apache.ws.security.conversation.message.info.SecurityContextInfo;
  
  import java.util.Hashtable;
  
  /**
   * Class ConversationSession
   */
  public class ConversationSession {
  
      /**
       * The security context info of this session
       */
      private SecurityContextInfo contextInfo;
  
      /**
       * The set of derived keys used in the session
       * Here a Hashtable is used to list the derived keys by their id's
       * This will be useful when selecting the relevant derived key in the key derivator
       */
      private Hashtable derivedKeys;
  
      /**
       * Creates a new conversation session for a gien security context
       * 
       * @param contextInfo The security context info
       */
      public ConversationSession(SecurityContextInfo contextInfo) {
          this.contextInfo = contextInfo;
          this.derivedKeys = new Hashtable();
      }
  
      /**
       * Returns the security context info of this session
       * 
       * @return the security context info of this session
       */
      public SecurityContextInfo getContextInfo() {
          return contextInfo;
      }
  
      /**
       * Returns the Hashtable of derived keys (<code>DerivedKeyInfo</code> obects) of
       * this session
       * 
       * @return A Hashtable of DerivedKeyInfo objects
       */
      public Hashtable getDerivedKeys() {
          return derivedKeys;
      }
  
      /**
       * This adds a derived key into the session
       * 
       * @param dkInfo The info object of the relevant derived key
       */
      public void addDerivedKey(DerivedKeyInfo dkInfo) {
          this.derivedKeys.put(dkInfo.getId(), dkInfo);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationUtil.java
  
  Index: ConversationUtil.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import java.security.NoSuchAlgorithmException;
  import java.security.SecureRandom;
  import java.util.Random;
  
  /**
   * Class ConversationUtil
   */
  public class ConversationUtil {
  
      /**
       * This is the seperator used in the identifier, which is set in the Callback class
       * when it is used to get a key from the key derivator
       * The identifier is the combination of the uuid of the security context and
       * the nonce of the derived key token using which the key should be derived
       */
      private static final String ID_SEPARATER = "$$$$";
  
      // PX2HKO4TotXxjI6NuZ3MVQ==
      // 4gwgpDksuZsRy7bnontCw==
  
      /**
       * Genearets the nonce for a given length.
       * More comments...
       * 
       * @param length 
       * @return 
       */
      public String generateNonce(int length) {
          String nonce = "";    // he he
          Random nonceIntGen = new Random();
          float tempVal;
          String allChars =
                  "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz/=1234567890";
  
          // need more ???//
          for (int i = 0; i <= length; i++) {
              tempVal = nonceIntGen.nextFloat();
              int lengthOfCharSet = allChars.length() - 1;
              int charAt = Math.round(lengthOfCharSet * tempVal);
              nonce += allChars.charAt(charAt);
          }
          return nonce;
      }
  
      /**
       * @param identifier 
       * @return 
       * @see getUuidAndDerivedKeyTokenId()
       */
      public static String getDerivedKeyTokenId(String identifier) {
          return getUuidAndDerivedKeyTokenId(identifier)[1];
      }
  
      /**
       * @param identifier 
       * @return 
       * @see getUuidAndDerivedKeyTokenId()
       */
      public static String getUuid(String identifier) {
          return getUuidAndDerivedKeyTokenId(identifier)[0];
      }
  
      /**
       * This extracts the Uuid and the DerivedKeyTokenId from the identifier sent in
       * 
       * @param identifier The identifier in uuid[ConvUtil.ID_SEPARATOR]nonce format
       * @return A String arrasy of size 2 with uuid as the forst character and the nonce as the second
       */
      public static String[] getUuidAndDerivedKeyTokenId(String identifier) {
          String[] returnValue = new String[2];
          int uuidEnd =
                  identifier.indexOf(ConversationUtil.ID_SEPARATER);
  
          // Extract the uuid
          returnValue[0] = identifier.substring(0, uuidEnd);
  
          // Extract the DerivedKeyTokenId
          returnValue[1] = identifier.substring(uuidEnd + ConversationUtil.ID_SEPARATER.length(),
                  identifier.length());
          return returnValue;
      }
  
      /**
       * This generates the identifier string using the uuig and the nonce
       * 
       * @param uuid              The uuid
       * @param nonce             The DerivedKeyTokenId
       * @param derivedKeyTokenId 
       * @return generated identifier string
       */
      public static String generateIdentifier(String uuid,
                                              String derivedKeyTokenId) {
          return uuid + ConversationUtil.ID_SEPARATER + derivedKeyTokenId;
      }
  
      /**
       * Method genericID
       * 
       * @return 
       */
      public static String genericID() {
          try {
              SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
              byte[] genIDValue = new byte[6];
              random.nextBytes(genIDValue);
              return new String(genIDValue);
          } catch (NoSuchAlgorithmException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
              return null;
          }
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyCallbackHandler.java
  
  Index: DerivedKeyCallbackHandler.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import org.apache.ws.security.WSPasswordCallback;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.conversation.message.info.DerivedKeyInfo;
  import org.apache.ws.security.conversation.message.info.SecurityContextInfo;
  
  import javax.security.auth.callback.Callback;
  import javax.security.auth.callback.CallbackHandler;
  import javax.security.auth.callback.UnsupportedCallbackException;
  import java.util.Hashtable;
  
  /**
   * Class DerivedKeyCallbackHandler
   */
  public class DerivedKeyCallbackHandler implements CallbackHandler {
  
      /**
       * The set of all the sessions
       */
      public static Hashtable conversationSessionTable = new Hashtable();
  
      /**
       * @param uuid 
       * @param info 
       */
      public static void addSecurtiyContext(String uuid,
                                            SecurityContextInfo info) {
          // Create a new conversation session and add it to the session list
          conversationSessionTable.put(uuid, new ConversationSession(info));
      }
  
      // 
      // /**
      // * <strong>This should not be used</strong>
      // * @param uuid
      // * @param dkt
      // */
      // public void addDerivedKeyToken(String uuid, DerivedKeyToken dkt) throws ConversationException{
      // this.addDerivedKey(uuid,new DerivedKeyInfo(dkt));
      // }
  
      /**
       * Adds a derived key into a session identified by the uuid
       * 
       * @param uuid   The uuid of the session
       * @param dkInfo The derived key as a <code>DerivedKeyInfo</code> object
       * @throws ConversationException If the uuid is not in the list of sessions
       *                               <b>This should be done here and not in the <code>handle</code> method since for example if the session is expired
       *                               the request should not pass this point</b>
       *                               In the scenario that we'r concerned here one party creates a derived key, encryps the message with it and sends
       *                               The receiver should decrypt the message with that derived key. Therefore if the session is expired
       *                               that fact will  be only evident at this point where, the derived key is being added into the relevant session.
       */
      public void addDerivedKey(String uuid, DerivedKeyInfo dkInfo)
              throws ConversationException {
          ConversationSession convSess =
                  (ConversationSession) this.conversationSessionTable.get(uuid);
          if (convSess != null) {
              ((ConversationSession) this.conversationSessionTable.get(uuid)).addDerivedKey(dkInfo);
          } else {
              throw new ConversationException("The error not set yet : ref 1");
  
              /** @todo Handle this error properly */
  
              // This place can be reached
              // 1. If the session is expired
              // 2. If a wrong security context token is sent in (may be by some intruder)
              // 3. Will list more as and when I realize them :D
          }
      }
  
      /**
       * @param callbacks 
       * @throws UnsupportedCallbackException 
       */
      public void handle(Callback[] callbacks)
              throws UnsupportedCallbackException {
          for (int i = 0; i < callbacks.length; i++) {
              WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
              String keyId = pc.getIdentifer();
  
              // This will not be kept static
              KeyDerivator kd = new KeyDerivator(true, 16);
              try {
                  kd.generateKey(this.conversationSessionTable, keyId);
              } catch (ConversationException ex1) {
              } catch (WSSecurityException ex1) {
              }
  
              // KeyDerivator.generateKey(this.conversationSessionTable, keyId);
              pc.setPassword("security");
  
              /** Field key */
              byte[] key = {
                  (byte) 0x31, (byte) 0xfd, (byte) 0xcb, (byte) 0xda, (byte) 0xfb,
                  (byte) 0xcd, (byte) 0x6b, (byte) 0xa8, (byte) 0xe6, (byte) 0x19,
                  (byte) 0xa7, (byte) 0xbf, (byte) 0x51, (byte) 0xf7, (byte) 0xc7,
                  (byte) 0x3e, (byte) 0x80, (byte) 0xae, (byte) 0x98, (byte) 0x51,
                  (byte) 0xc8, (byte) 0x51, (byte) 0x34, (byte) 0x04
              };
              pc.setKey(key);
          }
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyTokenAdder.java
  
  Index: DerivedKeyTokenAdder.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import org.apache.ws.security.conversation.message.token.DerivedKeyToken;
  import org.apache.ws.security.message.WSBaseMessage;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  /**
   * Class DerivedKeyTokenAdder
   */
  public class DerivedKeyTokenAdder extends WSBaseMessage {
  
      /**
       * Method build
       * 
       * @param doc     
       * @param dkToken 
       * @return 
       */
      public Document build(Document doc,
                            DerivedKeyToken dkToken) {    // throws Exception {
  
          // log.debug("Begin add username token...");
          Element securityHeader = insertSecurityHeader(doc);
          WSSecurityUtil.appendChildElement(doc, securityHeader,
                  dkToken.getElement());
          return doc;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/KeyDerivator.java
  
  Index: KeyDerivator.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation;
  
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.conversation.message.info.DerivedKeyInfo;
  import org.apache.ws.security.message.token.SecurityTokenReference;
  
  import java.util.Hashtable;
  
  /**
   * Class KeyDerivator
   */
  public class KeyDerivator {
  
      /**
       * Field useFixedSizeKeys
       */
      private boolean useFixedSizeKeys = true;
  
      /**
       * Field keySize
       */
      private long keySize = 16;
  
      /**
       * Constructor KeyDerivator
       * 
       * @param useFixedSizeKeys 
       * @param keySize          
       */
      public KeyDerivator(boolean useFixedSizeKeys, long keySize) {
          this.useFixedSizeKeys = useFixedSizeKeys;
          this.keySize = keySize;
      }
  
      /**
       * Method generateKey
       * 
       * @param sessionTable 
       * @param identifier   
       * @return 
       * @throws WSSecurityException   
       * @throws ConversationException 
       * @throws WSSecurityException   
       */
      public String generateKey(Hashtable sessionTable, String identifier)
              throws WSSecurityException, ConversationException,
              WSSecurityException {
          String[] uuidAndDerivedKeyTokenId =
                  ConversationUtil.getUuidAndDerivedKeyTokenId(identifier);
  
          // Get the session from teh session table
          ConversationSession convSession =
                  (ConversationSession) sessionTable.get(uuidAndDerivedKeyTokenId[0]);
          int freq =
                  convSession.getContextInfo().getFrequency();
  
          // Key generation frequency
          if (freq == 0) {
              // If the frequency is zero then no need for key derivation
              return convSession.getContextInfo().getSharedSecret().toString();
          } else {    // Derived keys are required
              return deriveKey(convSession, uuidAndDerivedKeyTokenId[1]);
          }
      }
  
      /**
       * Method deriveKey
       * 
       * @param convSession       
       * @param derivedKeyTokenId 
       * @return 
       * @throws WSSecurityException   
       * @throws ConversationException 
       */
      private String deriveKey(ConversationSession convSession, String derivedKeyTokenId)
              throws WSSecurityException, ConversationException {
          // The derived key info object of the current derived key
          DerivedKeyInfo dkInfo =
                  (DerivedKeyInfo) convSession.getDerivedKeys().get(derivedKeyTokenId);
          SecurityTokenReference secTokRef = dkInfo.getSecurityTokenReference();
          if (secTokRef != null) {
              String contextIdentifier =
                      convSession.getContextInfo().getIdentifier();
              if (secTokRef.getReference().getURI().equals(contextIdentifier)) {
                  // If the reference is to the SecurityContextToken
                  return deriveTokenFromContext(convSession, dkInfo);
              }
          } else {    // There is no SecurityTokenRefernece
              return deriveTokenFromContext(convSession, dkInfo);
          }
          return "ThisIsNotDoneYet";
      }
  
      /**
       * Method deriveTokenFromContext
       * 
       * @param convSession 
       * @param dkInfo      
       * @return 
       * @throws ConversationException 
       */
      private String deriveTokenFromContext(ConversationSession convSession, DerivedKeyInfo dkInfo)
              throws ConversationException {
          String secret =
                  convSession.getContextInfo().getSharedSecret().toString();
  
          // If the derivator is not configurad to use fixed size keys and there is no length information
          if ((!useFixedSizeKeys) && (dkInfo.getLength() == -1)) {
          }
          if (dkInfo.getGeneration() != -1) {    // Generation info present
          } else {                               // No generation info
          }
          return "";
      }
  
      /**
       * Method useFixedSizeKeys
       * 
       * @param usage 
       */
      public void useFixedSizeKeys(boolean usage) {
      }
  
      /**
       * Method useFixedSizeKeys
       * 
       * @param usage  
       * @param length 
       */
      public void useFixedSizeKeys(boolean usage, long length) {
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/DerivedKeyInfo.java
  
  Index: DerivedKeyInfo.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.message.info;
  
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.conversation.message.token.DerivedKeyToken;
  import org.apache.ws.security.message.token.SecurityTokenReference;
  
  import java.util.Hashtable;
  
  /**
   * Class DerivedKeyInfo
   */
  public class DerivedKeyInfo {
  
      /**
       * Field properties
       */
      private Hashtable properties;
  
      /**
       * Field id
       */
      private String id;
  
      /**
       * Field generation
       */
      private int generation;
  
      /**
       * Field offset
       */
      private int offset;
  
      /**
       * Field length
       */
      private long length;
  
      /**
       * Field label
       */
      private String label;
  
      /**
       * Field nonce
       */
      private String nonce;
  
      /**
       * Field usageCount
       */
      private int usageCount;
  
      /**
       * Field secTokenRef
       */
      private SecurityTokenReference secTokenRef;
  
      /**
       * Constructor DerivedKeyInfo
       * 
       * @param dkt 
       * @throws WSSecurityException 
       */
      public DerivedKeyInfo(DerivedKeyToken dkt) throws WSSecurityException {
          this.properties = dkt.getProperties();
          this.generation = dkt.getGeneration();
          this.offset = dkt.getOffset();
          this.length = dkt.getLength();
          this.label = dkt.getLabel();
          this.nonce = dkt.getNonce();
          this.id = dkt.getID();
  
          // I need this info in the KeyDerivator
          // Please feel free to suggest a better method to get the reference info into the KeyDerivator
          this.secTokenRef = dkt.getSecuityTokenReference();
      }
  
      /**
       * Method getGeneration
       * 
       * @return 
       */
      public int getGeneration() {
          return generation;
      }
  
      /**
       * Method getLabel
       * 
       * @return 
       */
      public String getLabel() {
          return label;
      }
  
      /**
       * Method getLength
       * 
       * @return 
       */
      public long getLength() {
          return length;
      }
  
      /**
       * Method getNonce
       * 
       * @return 
       */
      public String getNonce() {
          return nonce;
      }
  
      /**
       * Method getOffset
       * 
       * @return 
       */
      public int getOffset() {
          return offset;
      }
  
      /**
       * Method getProperties
       * 
       * @return 
       */
      public Hashtable getProperties() {
          return properties;
      }
  
      /**
       * Method getId
       * 
       * @return 
       */
      public String getId() {
          return id;
      }
  
      /**
       * Method getSecurityTokenReference
       * 
       * @return 
       */
      public SecurityTokenReference getSecurityTokenReference() {
          return secTokenRef;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/SecurityContextInfo.java
  
  Index: SecurityContextInfo.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.conversation.message.info;
  
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.conversation.message.token.RequestedProofToken;
  import org.apache.ws.security.conversation.message.token.SecurityContextToken;
  
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.Date;
  import java.util.TimeZone;
  
  /**
   * Class SecurityContextInfo
   */
  public class SecurityContextInfo {
  
      /**
       * Field sharedSecret
       */
      private byte[] sharedSecret;
  
      /**
       * Field expiration
       */
      private String expiration;
  
      /**
       * Field expirationDate
       */
      private Date expirationDate;
  
      /**
       * Field identifier
       */
      private String identifier;
  
      /**
       * Field frequency
       */
      private int frequency;
  
      /**
       * This element will be useful to store in the hashtable to get
       * information about the security context
       * 
       * @param securityContextToken 
       * @param requestedProofToken  
       * @param frequency            
       * @throws WSSecurityException 
       */
      public SecurityContextInfo(SecurityContextToken securityContextToken, RequestedProofToken requestedProofToken, int frequency)
              throws WSSecurityException {
          this.sharedSecret = requestedProofToken.getSharedSecret();
  
          // call the public method to set both string and the date value
          this.setExpiration(securityContextToken.getExpires());    // wrong : Ruchith--> Need to provide a method to get Expiration
          this.identifier = securityContextToken.getIdentifier();
          this.frequency = frequency;    // frequency of refreshing the derrived key
  
          // check for nullity throw exceptions
      }
  
      /**
       * This constructor will be useful to create a SecurityContextInfo object
       * without having SecurityContextToken and RequestedProofToken
       * Specially for testing purposes
       * 
       * @param sharedSecret 
       * @param expiration   
       * @param frequency    
       * @throws WSSecurityException 
       */
      public SecurityContextInfo(byte[] sharedSecret, String expiration, int frequency)
              throws WSSecurityException {
          this.sharedSecret = sharedSecret;
  
          // call the public method to set both string and the date value
          this.setExpiration(expiration);
          this.frequency = frequency;
      }
  
      /**
       * @return shared secret
       */
      public byte[] getSharedSecret() {
          return this.sharedSecret;
      }
  
      /**
       * @return shared secret as a byte array
       */
      public byte[] getSharedSecretAsByteArray() {
          return this.sharedSecret;
      }
  
      /**
       * @return expiration date
       */
      public String getexpiration() {
          return this.expiration;
      }
  
      /**
       * Set expiration date
       * 
       * @param created    
       * @param expiration 
       * @throws WSSecurityException 
       */
      public void setExpiration(String expiration) throws WSSecurityException {
          this.expiration = expiration;
          this.expirationDate = this.getDate(expiration);
      }
  
      /**
       * @return 
       */
      public String getIdentifier() {
          return this.identifier;
      }
  
      /**
       * @return frequency of refreshing the derrived key
       */
      public int getFrequency() {
          return frequency;
      }
  
      /**
       * @param frequency : frequency of refreshing the derrived key
       */
      public void setFrequency(int frequency) {
          this.frequency = frequency;
      }
  
      /**
       * @return 
       * @throws WSSecurityException 
       */
      public boolean isExpired() throws WSSecurityException {
          boolean isExpired;
          Calendar rightNow = Calendar.getInstance();
          SimpleDateFormat zulu =
                  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
          zulu.setTimeZone(TimeZone.getTimeZone("GMT"));
  
          // go through the same process  to current time as the expiration time
          // before the comparison
          Date date = this.getDate(zulu.format(rightNow.getTime()));
  
          // if the expiration is before current time return to
          isExpired = this.expirationDate.before(date);
          return isExpired;
      }
  
      /**
       * To get a Date object given a string(Expiration date)
       * E.g. 2001-10-13T09:00:00Z
       * Shall we put these functions in a util packege
       * WSConversation.util will be handy :)
       * 
       * @param strDate 
       * @return 
       * @throws WSSecurityException 
       */
      private Date getDate(String strDate) throws WSSecurityException {
          Date date;
          System.out.println("Date is ::" + strDate);
          try {
              // Date "T" Time
              String[] dateTimeSplits = strDate.split("T");
              String strDatePart = dateTimeSplits[0].trim();
              String strTimePart = dateTimeSplits[1].trim();
  
              // Date 2001-10-13
              String[] dateSplits = strDatePart.split("-");
              String sYear = dateSplits[0].trim();
              String sMonth = dateSplits[1].trim();
              String sDate = dateSplits[2].trim();
  
              // Time 09:00:00Z
              String[] timeSplits = strTimePart.split(":");
              String sHr = timeSplits[0].trim();
              String sMin = timeSplits[1].trim();
              String sSec = timeSplits[2].replace('Z', ' ').trim();
              date = new Date(Integer.parseInt(sYear), Integer.parseInt(sMonth),
                      Integer.parseInt(sDate), Integer.parseInt(sHr),
                      Integer.parseInt(sMin), Integer.parseInt(sSec));
          } catch (Exception e) {
              throw new WSSecurityException(WSSecurityException.FAILURE,
                      "Can not convert to a date");
          }
          return date;
      }
  
      /**
       * @param bs 
       */
      public void setSharedSecret(byte[] bs) {
          sharedSecret = bs;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust/TrustConstants.java
  
  Index: TrustConstants.java
  ===================================================================
  /*
   * Copyright  2003-2004 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.trust;
  
  /**
   * @author Malinda Kaushalye
   *
   * Place to keep constants for WS-Trust.
   * Please refer the specification for further clarification.
   */
  public class TrustConstants {
  
    public static final String SECURITY_CONTEXT_TOKEN_RESPONSE_LN ="SecurityContextTokenResponse";
    public static final String TOKEN_TYPE_LN = "TokenType";
    public static final String KEY_TYPE_LN = "KeyType";
    public static final String KEY_SIZE_LN = "KeySize";
  
    public static final String LIFE_TIME_LN = "Lifetime";
    public static final String REQUESTED_SECURITY_TOKEN_LN = "RequestedSecurityToken";
  
    public static final String SECURITY_CONTEXT_TOKEN_LN = "String SecurityContextToken";
  
   }
  
  
  
  
  1.15      +35 -3     ws-fx/wss4j/src/org/apache/ws/security/message/WSEncryptBody.java
  
  Index: WSEncryptBody.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/message/WSEncryptBody.java,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- WSEncryptBody.java	2 Jun 2004 19:35:44 -0000	1.14
  +++ WSEncryptBody.java	18 Jun 2004 11:33:03 -0000	1.15
  @@ -68,6 +68,16 @@
   	protected byte[] embeddedKey = null;
   	protected String embeddedKeyName = null;
   	protected X509Certificate useThisCert = null;
  +	
  +	/**
  +	 * Symmetric key used in the EncrytpedKey. 
  +	 */
  +	protected SecretKey symmetricKey=null;
  +	
  +	/**
  +	 * Parent node to which the EncryptedKeyElement should be added.
  +	 */
  +	protected Element parentNode = null;
   
   	/**
   	 * Constructor.
  @@ -420,12 +430,19 @@
   		 */
   		Element wsseSecurity = insertSecurityHeader(doc);
   		Element xencEncryptedKey = createEnrcyptedKey(doc, keyEncAlgo);
  +		if(parentNode==null){		
   		WSSecurityUtil.prependChildElement(
   			doc,
   			wsseSecurity,
   			xencEncryptedKey,
   			true);
  -
  +		}else{
  +			WSSecurityUtil.prependChildElement(
  +						doc,
  +						parentNode,
  +						xencEncryptedKey,
  +						true);
  +		} 
   		SecurityTokenReference secToken = new SecurityTokenReference(doc);
   
   		switch (keyIdentifierType) {
  @@ -517,8 +534,7 @@
   		 * key (password) for this alogrithm, and set the cipher into 
   		 * encryption mode. 
   		 */
  -		SecretKey symmetricKey = null;
  -
  +		
   		symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
   
   		XMLCipher xmlCipher = null;
  @@ -699,4 +715,20 @@
   		WSSecurityUtil.appendChildElement(doc, encryptedKey, referenceList);
   		return referenceList;
   	}
  +	
  +	/**
  +	 * Sets the parent node of the EncryptedKeyElement
  +	 * @param element
  +	 */
  +	public void setParentNode(Element element) {
  +		parentNode = element;
  +	}
  +
  +    /**
  +     * @return
  +     */
  +    public SecretKey getSymmetricKey() {
  +        return symmetricKey;
  +    }
  +
   }