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 mu...@apache.org on 2004/10/16 08:06:54 UTC

cvs commit: ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token RequestSecurityTokenResponse.java DerivedKeyToken.java RequestedProofToken.java

muthulee    2004/10/15 23:06:54

  Modified:    wss4j/src/org/apache/ws/security/conversation
                        ConversationUtil.java ConversationConstants.java
                        ConversationEngine.java DerivedKeyTokenAdder.java
                        ConversationSession.java KeyDerivator.java
                        DerivedKeyCallbackHandler.java
                        ConversationManager.java
               wss4j/src/org/apache/ws/security/conversation/message/info
                        SecurityContextInfo.java DerivedKeyInfo.java
               wss4j/src/org/apache/ws/security/conversation/message/token
                        RequestSecurityTokenResponse.java
                        DerivedKeyToken.java RequestedProofToken.java
  Log:
  Performing changes to the core components of
  Secure Conversation in order to support Interop scenarios.
  Dimuthu and Ruchith
  
  Revision  Changes    Path
  1.7       +2 -2      ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationUtil.java
  
  Index: ConversationUtil.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationUtil.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- ConversationUtil.java	9 Aug 2004 18:02:47 -0000	1.6
  +++ ConversationUtil.java	16 Oct 2004 06:06:53 -0000	1.7
  @@ -43,7 +43,7 @@
       private static final String ID_SEPARATER = "$$$$";
   
       /**
  -     * Genearets the nonce for a given length.
  +     * Genearets the nonce for a given bit length.
        */
       public static String generateNonce(int length) {
           SecureRandom random = null;
  @@ -53,7 +53,7 @@
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
  -        byte[] nonceValue = new byte[length];
  +        byte[] nonceValue = new byte[length/8];
           random.nextBytes(nonceValue);
           return Base64.encode(nonceValue);
       }
  
  
  
  1.4       +2 -1      ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationConstants.java
  
  Index: ConversationConstants.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationConstants.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- ConversationConstants.java	9 Aug 2004 17:53:43 -0000	1.3
  +++ ConversationConstants.java	16 Oct 2004 06:06:53 -0000	1.4
  @@ -96,7 +96,8 @@
   
       public static final int DIRECT_GENERATED = 1;
       public static final int STS_GENERATED = 2;
  -    public static final int WS_GENERATED = 3;
  +    public static final int STSREQUEST_TOKEN = 3;
  +    public static final int INTEROP_SCENE1 = 4;
   
       public static final String IDENTIFIER = "SCT_Identifier";
   
  
  
  
  1.5       +494 -196  ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationEngine.java
  
  Index: ConversationEngine.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationEngine.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ConversationEngine.java	30 Aug 2004 05:55:39 -0000	1.4
  +++ ConversationEngine.java	16 Oct 2004 06:06:53 -0000	1.5
  @@ -26,15 +26,24 @@
   import org.apache.ws.security.WSDocInfoStore;
   import org.apache.ws.security.WSPasswordCallback;
   import org.apache.ws.security.WSSConfig;
  +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.conversation.message.info.DerivedKeyInfo;
   import org.apache.ws.security.conversation.message.info.SecurityContextInfo;
   import org.apache.ws.security.conversation.message.token.DerivedKeyToken;
  -import org.apache.ws.security.conversation.message.token.RequestSecurityTokenResponse;
  +import org
  +    .apache
  +    .ws
  +    .security
  +    .conversation
  +    .message
  +    .token
  +    .RequestSecurityTokenResponse;
   import org.apache.ws.security.conversation.message.token.RequestedProofToken;
   import org.apache.ws.security.conversation.message.token.SecurityContextToken;
  +import org.apache.ws.security.handler.WSHandlerConstants;
   import org.apache.ws.security.message.EnvelopeIdResolver;
   import org.apache.ws.security.message.token.Reference;
   import org.apache.ws.security.message.token.SecurityTokenReference;
  @@ -48,19 +57,30 @@
   import org.apache.xml.security.keys.KeyInfo;
   import org.apache.xml.security.signature.XMLSignature;
   import org.apache.xml.security.signature.XMLSignatureException;
  +import org.apache.xml.security.utils.XMLUtils;
  +import org.opensaml.SAMLAssertion;
  +import org.opensaml.SAMLAuthenticationStatement;
  +import org.opensaml.SAMLException;
   import org.w3c.dom.Attr;
   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.crypto.KeyGenerator;
   import javax.crypto.SecretKey;
   import javax.crypto.spec.SecretKeySpec;
   import javax.security.auth.callback.Callback;
  +import javax.security.auth.callback.CallbackHandler;
   import javax.security.auth.callback.UnsupportedCallbackException;
   import javax.xml.namespace.QName;
  +
  +import java.io.ByteArrayOutputStream;
   import java.io.IOException;
  +import java.io.UnsupportedEncodingException;
   import java.util.HashMap;
  +import java.util.Iterator;
   import java.util.Vector;
   
   /**
  @@ -70,7 +90,7 @@
    */
   public class ConversationEngine {
       private static Log log =
  -            LogFactory.getLog(ConversationEngine.class.getName());
  +        LogFactory.getLog(ConversationEngine.class.getName());
       private static Log tlog = LogFactory.getLog("org.apache.ws.security.TIME");
   
       private boolean doDebug = false;
  @@ -79,31 +99,34 @@
        * <code>wsc:DerivedKeyToken</code> as defined in WS Secure Conversation specification.
        */
       protected static final QName DERIVEDKEY_TOKEN =
  -            new QName(ConversationConstants.WSC_NS,
  -                    ConversationConstants.DERIVED_KEY_TOKEN_LN);
  +        new QName(
  +            ConversationConstants.WSC_NS,
  +            ConversationConstants.DERIVED_KEY_TOKEN_LN);
   
       /**
        * <code>wsc:SecurityContextToken</code> as defined in WS Secure Conversation specification.
        */
       protected static final QName SCT_TOKEN =
  -            new QName(ConversationConstants.WSC_NS,
  -                    ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
  +        new QName(
  +            ConversationConstants.WSC_NS,
  +            ConversationConstants.SECURITY_CONTEXT_TOKEN_LN);
       /**
        * Refer WS secure Conversation specification
        */
       protected static final QName REQUESTED_SECURITY_TOKEN_RESPONSE =
  -            new QName(TrustConstants.WST_NS,
  -                    TrustConstants.REQUEST_SECURITY_TOKEN_RESPONSE_LN);
  +        new QName(
  +            TrustConstants.WST_NS,
  +            TrustConstants.REQUEST_SECURITY_TOKEN_RESPONSE_LN);
       /**
        * <code>ds:Signature</code> as defined by XML Signature specification.
        */
       protected static final QName SIGNATURE =
  -            new QName(WSConstants.SIG_NS, WSConstants.SIG_LN);
  +        new QName(WSConstants.SIG_NS, WSConstants.SIG_LN);
       /**
        * <code>xenc:ReferenceList</code> as defined by XML Encryption specification,
        */
       protected static final QName REFERENCE_LIST =
  -            new QName(WSConstants.ENC_NS, WSConstants.REF_LIST_LN);
  +        new QName(WSConstants.ENC_NS, WSConstants.REF_LIST_LN);
   
       protected static final QName SCT = SecurityContextToken.TOKEN;
   
  @@ -122,13 +145,18 @@
       public ConversationEngine(HashMap config) {
   
           this.configurator = config;
  +        //TODO :: Move this out of here.
           Boolean bool = null;
  -        if ((bool = (Boolean) configurator.get(ConvHandlerConstants.VERIFY_TRUST)) == null) {
  +        if ((bool =
  +            (Boolean) configurator.get(ConvHandlerConstants.VERIFY_TRUST))
  +            == null) {
   
           } else {
               this.verifyTrust = bool.booleanValue();
               if (verifyTrust) {
  -                this.trustPropFile = (String) configurator.get(ConvHandlerConstants.TRUST_ENGINE_PROP);
  +                this.trustPropFile =
  +                    (String) configurator.get(
  +                        ConvHandlerConstants.TRUST_ENGINE_PROP);
               }
           }
       }
  @@ -143,10 +171,12 @@
        * @throws ConversationException
        */
   
  -    public Vector processSecConvHeader(Document doc,
  -                                       String actor,
  -                                       DerivedKeyCallbackHandler dkcb, String callback)
  -            throws ConversationException {
  +    public Vector processSecConvHeader(
  +        Document doc,
  +        String actor,
  +        DerivedKeyCallbackHandler dkcb,
  +        String callback)
  +        throws ConversationException {
   
           doDebug = log.isDebugEnabled();
           if (doDebug) {
  @@ -157,8 +187,9 @@
               actor = "";
           }
           NodeList list =
  -                doc.getElementsByTagNameNS(WSConstants.WSSE_NS,
  -                        WSConstants.WSSE_LN);
  +            doc.getElementsByTagNameNS(
  +                WSConstants.WSSE_NS,
  +                WSConstants.WSSE_LN);
           int len = list.getLength();
           if (len == 0) { // No Security headers found
               return null;
  @@ -170,23 +201,25 @@
           Attr attr = null;
           String headerActor = null;
           SOAPConstants sc =
  -                WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
  +            WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
           Vector convResult = new Vector();
   
           for (int i = 0; i < len; i++) {
               elem = (Element) list.item(i);
               attr =
  -                    elem.getAttributeNodeNS(sc.getEnvelopeURI(),
  -                            sc.getRoleAttributeQName().getLocalPart());
  +                elem.getAttributeNodeNS(
  +                    sc.getEnvelopeURI(),
  +                    sc.getRoleAttributeQName().getLocalPart());
               if (attr != null) {
                   headerActor = attr.getValue();
               }
               if ((headerActor == null)
  -                    || (headerActor.length() == 0)
  -                    || headerActor.equalsIgnoreCase(actor)
  -                    || headerActor.equals(sc.getNextRoleURI())) {
  +                || (headerActor.length() == 0)
  +                || headerActor.equalsIgnoreCase(actor)
  +                || headerActor.equals(sc.getNextRoleURI())) {
                   if (doDebug) {
  -                    log.debug("Processing WS-Security header for '"
  +                    log.debug(
  +                        "Processing WS-Security header for '"
                               + actor
                               + "' actor.");
                   }
  @@ -212,10 +245,12 @@
        * @throws ConversationException
        */
   
  -    protected Vector processConvHeader(Element securityHeader,
  -                                       Document doc,
  -                                       DerivedKeyCallbackHandler dkcbHandler, String callback)
  -            throws ConversationException, WSSecurityException {
  +    protected Vector processConvHeader(
  +        Element securityHeader,
  +        Document doc,
  +        DerivedKeyCallbackHandler dkcbHandler,
  +        String callback)
  +        throws ConversationException, WSSecurityException {
   
           long t0 = 0, t1 = 0, t2 = 0;
           if (tlog.isDebugEnabled()) {
  @@ -246,16 +281,19 @@
                       log.debug("Found RequestedSecurityTokenResponse element");
                   }
   
  -                returnResults.add(this.handleRequestedSecurityTokenResponse((Element) elem,
  -                        dkcbHandler, callback));
  +                returnResults.add(
  +                    this.handleRequestedSecurityTokenResponse(
  +                        (Element) elem,
  +                        dkcbHandler,
  +                        callback));
   
               } else if (el.equals(SIGNATURE)) {
                   if (doDebug) {
                       log.debug("Found Signature element");
                   }
  -                //System.out.println("Signature " + i);
  +                
                   ConvEngineResult convResult =
  -                        this.VerifySignature((Element) elem, dkcbHandler);
  +                    this.VerifySignature((Element) elem, dkcbHandler);
                   returnResults.add(convResult);
               } else if (el.equals(REFERENCE_LIST)) {
                   if (doDebug) {
  @@ -263,14 +301,16 @@
   
                   }
                   Vector tmpVec =
  -                        handleReferenceList((Element) elem, dkcbHandler);
  +                    handleReferenceList((Element) elem, dkcbHandler);
                   for (int j = 0; j < tmpVec.size(); j++) {
                       returnResults.add(tmpVec.get(j));
                   }
               } else if (el.equals(SCT)) {
  -                SecurityContextToken sct = new SecurityContextToken((Element) elem);
  +                SecurityContextToken sct =
  +                    new SecurityContextToken((Element) elem);
                   String uuid = sct.getIdentifier();
  -                ConvEngineResult convResult = new ConvEngineResult(ConvEngineResult.SCT);
  +                ConvEngineResult convResult =
  +                    new ConvEngineResult(ConvEngineResult.SCT);
                   convResult.setUuid(uuid);
                   returnResults.add(convResult);
               }
  @@ -279,9 +319,11 @@
           return returnResults;
       }
   
  -    public ConvEngineResult handleRequestedSecurityTokenResponse(Element eleSTRes,
  -                                                                 DerivedKeyCallbackHandler dkcbHandler, String callback)
  -            throws ConversationException {
  +    public ConvEngineResult handleRequestedSecurityTokenResponse(
  +        Element eleSTRes,
  +        DerivedKeyCallbackHandler dkcbHandler,
  +        String callback)
  +        throws ConversationException {
           String uuid = null;
           RequestSecurityTokenResponse stRes = null;
   
  @@ -292,36 +334,30 @@
                   System.out.println("...........Verifying trust.........");
   
               }
  -                
  +
               //Now trust is verified.
  -                
  +
               stRes = new RequestSecurityTokenResponse(eleSTRes, true);
               SecurityContextToken SCT =
  -                    stRes.getRequestedSecurityToken().getSct();
  +                stRes.getRequestedSecurityToken().getSct();
               uuid = SCT.getIdentifier();
               RequestedProofToken proofToken = stRes.getRequestedProofToken();
               //TODO:: romove the hard coded decryption
  -                
  -            proofToken.doDecryption(callback,
  -                    loadEncryptionCrypto());
  +
  +            proofToken.doDecryption(callback, this.loadDecryptionCrypto());
   
               SecurityContextInfo scInfo = null;
               scInfo = new SecurityContextInfo(SCT, proofToken, 1);
   
               dkcbHandler.addSecurtiyContext(uuid, scInfo);
  -            boolean fixedKeyLen =
  -                    ((Boolean) this
  -                    .configurator
  -                    .get(ConvHandlerConstants.USE_FIXED_KEYLEN))
  -                    .booleanValue();
  -            if (fixedKeyLen) { //key legnth is varing
  -                dkcbHandler.setDerivedKeyLength(uuid,
  -                        ((Long) configurator.get(ConvHandlerConstants.KEY_LEGNTH))
  +                dkcbHandler.setDerivedKeyLength(
  +                    uuid,
  +                    ((Long) configurator.get(ConvHandlerConstants.KEY_LEGNTH))
                           .longValue());
  -            }
  -
  +          
               log.debug(" Done SecurityToekenResponse Handled");
  -            ConvEngineResult res = new ConvEngineResult(ConvEngineResult.SECURITY_TOKEN_RESPONSE);
  +            ConvEngineResult res =
  +                new ConvEngineResult(ConvEngineResult.SECURITY_TOKEN_RESPONSE);
               res.setUuid(uuid);
               return res;
   
  @@ -336,11 +372,17 @@
           }
       }
   
  -    private ConvEngineResult VerifySignature(Element elem,
  -                                             DerivedKeyCallbackHandler dkcbHandler)
  -            throws ConversationException {
  +    private ConvEngineResult VerifySignature(
  +        Element elem,
  +        DerivedKeyCallbackHandler dkcbHandler)
  +        throws ConversationException {
           ConvEngineResult convResult = null;
           XMLSignature sig = null;
  +//      System.out.println("******** at VerifySignature");
  +//		ByteArrayOutputStream os = new ByteArrayOutputStream();
  +//		XMLUtils.outputDOM(elem, os, true);
  +//		String osStr = os.toString();
  +//		System.out.println(osStr);
           try {
               sig = new XMLSignature(elem, null);
           } catch (XMLSignatureException e2) {
  @@ -358,7 +400,7 @@
               try {
                   //sign.verifiyXMLHMac_SHA1_Signarue(sig, dkcbHandler);
                   convResult =
  -                        this.verifiyXMLHMac_SHA1_Signarue(sig, dkcbHandler);
  +                    this.verifiyXMLHMac_SHA1_Signarue(sig, dkcbHandler);
               } catch (WSSecurityException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
  @@ -375,15 +417,16 @@
        * <p/>
        * Dereferences and decodes encrypted data elements.
        */
  -    private Vector handleReferenceList(Element elem,
  -                                       DerivedKeyCallbackHandler dkcbHandler)
  -            throws WSSecurityException {
  +    private Vector handleReferenceList(
  +        Element elem,
  +        DerivedKeyCallbackHandler dkcbHandler)
  +        throws WSSecurityException {
           Vector results = new Vector();
           Document doc = elem.getOwnerDocument();
           Node tmpE = null;
           for (tmpE = elem.getFirstChild();
  -             tmpE != null;
  -             tmpE = tmpE.getNextSibling()) {
  +            tmpE != null;
  +            tmpE = tmpE.getNextSibling()) {
               if (tmpE.getNodeType() != Node.ELEMENT_NODE) {
                   continue;
               }
  @@ -393,7 +436,7 @@
               if (tmpE.getLocalName().equals("DataReference")) {
                   String dataRefURI = ((Element) tmpE).getAttribute("URI");
                   ConvEngineResult convRes =
  -                        decryptDataRef(doc, dataRefURI, dkcbHandler);
  +                    decryptDataRef(doc, dataRefURI, dkcbHandler);
                   results.add((Object) convRes);
               } else if (tmpE.getLocalName().equals("KeyReference")) {
                   String keyRefURI = ((Element) tmpE).getAttribute("URI");
  @@ -402,10 +445,11 @@
           return results;
       }
   
  -    private ConvEngineResult decryptDataRef(Document doc,
  -                                            String dataRefURI,
  -                                            DerivedKeyCallbackHandler dkcbHandler)
  -            throws WSSecurityException {
  +    private ConvEngineResult decryptDataRef(
  +        Document doc,
  +        String dataRefURI,
  +        DerivedKeyCallbackHandler dkcbHandler)
  +        throws WSSecurityException {
   
           log.debug("ConversationEngine :: Found data refernce: " + dataRefURI);
   
  @@ -416,40 +460,48 @@
            */
           Element encBodyData = null;
           if ((encBodyData =
  -                WSSecurityUtil.getElementByWsuId(WSSConfig.getDefaultWSConfig(), doc, dataRefURI))
  -                == null) {
  +            WSSecurityUtil.getElementByWsuId(
  +                WSSConfig.getDefaultWSConfig(),
  +                doc,
  +                dataRefURI))
  +            == null) {
               encBodyData = WSSecurityUtil.getElementByGenId(doc, dataRefURI);
           }
           if (encBodyData == null) {
  -            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                    "dataRef",
  -                    new Object[]{dataRefURI});
  +            throw new WSSecurityException(
  +                WSSecurityException.INVALID_SECURITY,
  +                "dataRef",
  +                new Object[] { dataRefURI });
           }
   
           Element tmpE = null;
  -        log.debug("ConversationEngine :: Going to figure out the key to decrypt");
  +        log.debug(
  +            "ConversationEngine :: Going to figure out the key to decrypt");
           byte[] decryptedBytes = null;
  -           
  -        /*Decryption is performed in 3 major steps
  -         * 
  +
  +        /*
  +         * Decryption is performed in 3 major steps
            */
  -            
  +
           //Step 1 : Get the key from SecurityTokenReference.
  -            
  -        log.debug("ConversationEngine:: Going to look for SecurityTokenReference");
  +
  +        log.debug(
  +            "ConversationEngine:: Going to look for SecurityTokenReference");
   
           if ((tmpE =
  -                (Element) WSSecurityUtil.findElement((Node) encBodyData,
  -                        "SecurityTokenReference",
  -                        WSConstants.WSSE_NS))
  -                != null) {
  +            (Element) WSSecurityUtil.findElement(
  +                (Node) encBodyData,
  +                "SecurityTokenReference",
  +                WSSConfig.getDefaultWSConfig().getWsseNS()))
  +            != null) {
               SecurityTokenReference secRef =
  -                    new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), tmpE);
  +                new SecurityTokenReference(
  +                    WSSConfig.getDefaultWSConfig(),
  +                    tmpE);
   
               try {
                   convResult =
  -                        this.handleSecurityTokenReference(secRef,
  -                                dkcbHandler);
  +                    this.handleSecurityTokenReference(secRef, dkcbHandler);
                   decryptedBytes = convResult.getKeyAssociated();
               } catch (ConversationException e2) {
                   // TODO Auto-generated catch block
  @@ -459,48 +511,59 @@
           } else {
               //TODO:: Provide more info
               throw new WSSecurityException(WSSecurityException.FAILURE);
  -        } 
  -            
  +        }
  +
           // Step 2 :: Now figure out the encryption algorithm
           String symEncAlgo = getEncAlgo(encBodyData);
           SecretKey symmetricKey =
  -                WSSecurityUtil.prepareSecretKey(symEncAlgo, decryptedBytes);
  -        //System.out.println("Key is ::" + decryptedBytes);
  -            
  +            WSSecurityUtil.prepareSecretKey(symEncAlgo, decryptedBytes);
  +        
  +
           // Step 3 :: initialize Cipher ....
           XMLCipher xmlCipher = null;
           try {
               xmlCipher = XMLCipher.getInstance(symEncAlgo);
               xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
           } catch (XMLEncryptionException e1) {
  -            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM,
  -                    null,
  -                    null,
  -                    e1);
  -        } //TODO :: remove hard coding
  -        boolean content = true;
  +            throw new WSSecurityException(
  +                WSSecurityException.UNSUPPORTED_ALGORITHM,
  +                null,
  +                null,
  +                e1);
  +        }
  +        
  +        
  +     
  +		WSSecurityEngine eng = new WSSecurityEngine();
  +        boolean content = this.isContent(encBodyData);
  +        
           if (content) {
               encBodyData = (Element) encBodyData.getParentNode();
  +        }else{
  +        	System.out.println("Not content:-)");
           }
  +        
           try {
               xmlCipher.doFinal(doc, encBodyData, content);
           } catch (Exception e) {
  -            throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
  -                    null,
  -                    null,
  -                    e);
  +            throw new WSSecurityException(
  +                WSSecurityException.FAILED_ENC_DEC,
  +                null,
  +                null,
  +                e);
           }
           return convResult;
       }
   
  -    public ConvEngineResult handleSecurityTokenReference(SecurityTokenReference secRef,
  -                                                         DerivedKeyCallbackHandler dkcbHandler)
  -            throws ConversationException {
  +    public ConvEngineResult handleSecurityTokenReference(
  +        SecurityTokenReference secRef2DkToken,
  +        DerivedKeyCallbackHandler dkcbHandler)
  +        throws ConversationException {
   
  -        if (secRef.containsReference()) {
  +        if (secRef2DkToken.containsReference()) {
               Reference ref = null;
               try {
  -                ref = secRef.getReference();
  +                ref = secRef2DkToken.getReference();
               } catch (WSSecurityException e1) {
                   e1.printStackTrace();
                   throw new ConversationException(e1.getMessage());
  @@ -508,12 +571,13 @@
   
               String valueType = ref.getValueType();
               //  System.out.println("ref.getURI()" + ref.getURI());
  -                
  -            if (valueType.equals("DerivedKeyToken")) {
  +
  +            if (valueType.equals("http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk")) {
                   Element ele =
  -                        WSSecurityUtil.getElementByWsuId(WSSConfig.getDefaultWSConfig(),
  -                                secRef.getElement().getOwnerDocument(),
  -                                ref.getURI());
  +                    WSSecurityUtil.getElementByWsuId(
  +                        WSSConfig.getDefaultWSConfig(),
  +                        secRef2DkToken.getElement().getOwnerDocument(),
  +                        ref.getURI());
                   if (ele == null) {
                       throw new ConversationException("Cannot find  referenced Derived Key");
                   }
  @@ -521,13 +585,72 @@
                   DerivedKeyToken dkToken = null;
                   try {
                       dkToken = new DerivedKeyToken(ele);
  -                    SecurityContextToken secContextTk;
  -                    secContextTk = ConversationUtil.getSCT(dkToken);
  -                    uuid = secContextTk.getIdentifier();
  -                    //TODO :String uuid = secContextTk.getIdentifier();
  -                    log.debug("ConversationEngine :: The uuid is found " + uuid);
  -                    DerivedKeyInfo dkInfo = new DerivedKeyInfo(dkToken);
  -                    dkcbHandler.addDerivedKey(uuid, dkInfo);
  +                    if (dkToken.getSecuityTokenReference() == null) {
  +                        //if dkToken doesn't have a STR                    
  +                        SecurityContextToken secContextTk =
  +                            ConversationUtil.getSCT(dkToken);
  +                        uuid = secContextTk.getIdentifier();
  +                        log.debug(
  +                            "ConversationEngine :: The uuid is found " + uuid);
  +                        DerivedKeyInfo dkInfo = new DerivedKeyInfo(dkToken);
  +                        dkcbHandler.addDerivedKey(uuid, dkInfo);
  +                    } else { ///i.e. dkToken has a STR
  +                        SecurityTokenReference str2Base =
  +                            dkToken.getSecuityTokenReference();
  +                        if (str2Base.containsReference()) {
  +                            Reference ref2Base = str2Base.getReference();
  +                          
  +                            if (ref2Base
  +                                .getValueType()
  +                                .equals("http://docs.oasis-open.org/wss/2004/XX/oasis-2004XX-wss-saml-token-profile-1.0#SAMLAssertionID")) {
  +                                /* ok now I have a SAML token. What should I do ?
  +                                 * -Decrypt the secret.
  +                                 * -create tempUUID
  +                                 * -add the scTInfo into dkcbHandler
  +                                 * -add the derived key token to dkcbHandler.
  +                                 */
  +                               uuid = ref2Base.getURI();
  +                     		   if(dkcbHandler.getSession(uuid)==null){	 
  +						   	       byte[] key = handleSAML(ref2Base.getElement().getOwnerDocument(), uuid);
  +								   System.out.println("I am here :-)");
  +								   SecurityContextInfo sctInfo = new SecurityContextInfo(
  +																	   uuid,
  +																	   key,
  +																	   1);
  +								   dkcbHandler.addSecurtiyContext(
  +																	   uuid,
  +																	   sctInfo);
  +							   }		
  +									DerivedKeyInfo dkInfo = new DerivedKeyInfo(dkToken);
  +									dkcbHandler.addDerivedKey(uuid, dkInfo);
  +                            } 
  +                            
  +                            
  +                            
  +                            //TODO :: Add other tokens else if      
  +                        } else if(str2Base.containsKeyIdentifier()){
  +                        	Element elem = str2Base.getFirstElement();
  +                        	//.getKeyIdentifier()System.out.println("KeyIdentifier :: He ehee ........");
  +							String value = elem.getAttribute("ValueType");
  +							if("http://docs.oasis-open.org/wss/2004/XX/oasis-2004XX-wss-saml-token-profile-1.0#SAMLAssertionID".equals(value)){
  +								uuid = ((Text)elem.getChildNodes().item(0)).getNodeValue();
  +								if(dkcbHandler.getSession(uuid)==null){	 
  +									   byte[] key = handleSAML(elem.getOwnerDocument(), uuid);
  +									   System.out.println("UUID of SAML is"+uuid);
  +									   SecurityContextInfo sctInfo = new SecurityContextInfo(
  +																									   uuid,
  +																									   key,
  +																									   1);
  +									   dkcbHandler.addSecurtiyContext(uuid,sctInfo);
  +								}		
  +								DerivedKeyInfo dkInfo = new DerivedKeyInfo(dkToken);
  +								dkcbHandler.addDerivedKey(uuid, dkInfo);
  +							}
  +                        	
  +                        }else{
  +                            throw new ConversationException("Don't know how to process here");
  +                        }
  +                    } //////end :if dkToken has a STR
                       //TODO :: Ask ruchith to throw correct exception    
                   } catch (WSSecurityException e2) {
                       // TODO Auto-generated catch block
  @@ -538,11 +661,11 @@
                   }
   
                   String identifier =
  -                        ConversationUtil.generateIdentifier(uuid,
  -                                dkToken.getID());
  +                    ConversationUtil.generateIdentifier(uuid, dkToken.getID());
                   WSPasswordCallback pwCb =
  -                        new WSPasswordCallback(identifier,
  -                                WSPasswordCallback.UNKNOWN);
  +                    new WSPasswordCallback(
  +                        identifier,
  +                        WSPasswordCallback.UNKNOWN);
                   Callback[] callbacks = new Callback[1];
                   callbacks[0] = pwCb;
                   try {
  @@ -552,11 +675,12 @@
                       e.printStackTrace();
                   }
                   byte[] arr = pwCb.getKey();
  -                ConvEngineResult res = new ConvEngineResult(ConvEngineResult.ENCRYPT_DERIVED_KEY);
  +                ConvEngineResult res =
  +                    new ConvEngineResult(ConvEngineResult.ENCRYPT_DERIVED_KEY);
                   res.setKeyAssociated(arr);
                   return res;
               } else {
  -                throw new ConversationException("ConversationEngine :: SecurityTokenRerence doesn't contain refernce");
  +                throw new ConversationException("ConversationEngine :: SecurityTokenRerence doesn't contain DerivedKeys");
               }
           } else {
               throw new ConversationException("ConversationEngine ::SecurityTokenRerence doesn't contain refernce");
  @@ -569,9 +693,13 @@
        * @param cb  - Callback handler to get the symmetric key.
        * @return
        */
  -    private ConvEngineResult verifiyXMLHMac_SHA1_Signarue(XMLSignature sig,
  -                                                          DerivedKeyCallbackHandler dkcbHandler)
  -            throws WSSecurityException {
  +    private ConvEngineResult verifiyXMLHMac_SHA1_Signarue(
  +        XMLSignature sig,
  +        DerivedKeyCallbackHandler dkcbHandler)
  +        throws WSSecurityException {
  +        
  +        log.debug("Verifying HMAC-SHA1 Signature......");
  +	    	
           String userName = null;
           long t0 = 0, t1 = 0, t2 = 0;
           if (tlog.isDebugEnabled()) {
  @@ -579,82 +707,152 @@
           }
           ConvEngineResult convResult = null;
           if (sig == null) {
  -            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN,
  -                    "XMLSignature object is null");
  +            throw new WSSecurityException(
  +                WSSecurityException.INVALID_SECURITY_TOKEN,
  +                "XMLSignature object is null");
           } /* Following lines of code - upto WSDocInfoStore.lookup(docHash) is copied
  -                           * from the verifyXMLSignature() method.
  -                           *
  -                           */
  -
  -        sig.addResourceResolver(EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig()));
  +                                  * from the verifyXMLSignature() method.
  +                                  *
  +                                  */
  +       
  +        sig.addResourceResolver(
  +            EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig()));
           KeyInfo info = sig.getKeyInfo();
           if (info == null) {
  -            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                    "unsupportedKeyInfo");
  +            throw new WSSecurityException(
  +                WSSecurityException.INVALID_SECURITY,
  +                "unsupportedKeyInfo");
           }
           Node node =
  -                WSSecurityUtil.getDirectChild(info.getElement(),
  -                        SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
  -                        wssConfig.getWsseNS());
  +            WSSecurityUtil.getDirectChild(
  +                info.getElement(),
  +                SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
  +                wssConfig.getWsseNS());
           if (node == null) {
  -            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                    "unsupportedKeyInfo");
  +            throw new WSSecurityException(
  +                WSSecurityException.INVALID_SECURITY,
  +                "unsupportedKeyInfo");
           }
           SecurityTokenReference secRef =
  -                new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), (Element) node);
  -        int docHash = sig.getDocument().hashCode();
  +            new SecurityTokenReference(
  +                WSSConfig.getDefaultWSConfig(),
  +                (Element) node);
  +        Document docSig = sig.getDocument();
  +        int docHash = docSig.hashCode();
           if (doDebug) {
               log.debug("XML Verify doc: " + docHash);
           } /*
  -                           * Her we get some information about the document that is being processed,
  -                           * in partucular the crypto implementation, and already detected BST that
  -                           * may be used later during dereferencing.
  -                           */
  +                                  * Her we get some information about the document that is being processed,
  +                                  * in partucular the crypto implementation, and already detected BST that
  +                                  * may be used later during dereferencing.
  +                                  */
           WSDocInfo wsDocInfo = WSDocInfoStore.lookup(docHash);
           if (secRef.containsReference()) {
               Element token =
  -                    secRef.getTokenElement(sig.getDocument(), wsDocInfo);
  +                secRef.getTokenElement(sig.getDocument(), wsDocInfo);
               /* check token type: We support Derivedkey tokens now.
                * We will support security context tokens.
                */
  -            QName el =
  -                    new QName(token.getNamespaceURI(), token.getLocalName());
  +            QName el = new QName(token.getNamespaceURI(), token.getLocalName());
               if (el.equals(DERIVEDKEY_TOKEN)) {
                   DerivedKeyToken dkToken = new DerivedKeyToken(token);
  -                DerivedKeyInfo dkInfo = new DerivedKeyInfo(dkToken);
  -                SecurityContextToken sctTok = null;
  +                DerivedKeyInfo dkInfo = null;
  +                
  +				String uuid = null;
  +                
                   try {
  -                    sctTok = ConversationUtil.getSCT(dkToken);
  -                } catch (ConversationException e2) {
  -                    // TODO Auto-generated catch block
  -                    e2.printStackTrace();
  -                }
  -                String uuid = sctTok.getIdentifier();
  +					if (dkToken.getSecuityTokenReference() == null) {
  +						//if dkToken doesn't have a STR                    
  +						SecurityContextToken secContextTk =
  +							ConversationUtil.getSCT(dkToken);
  +						uuid = secContextTk.getIdentifier();
  +						log.debug(
  +							"ConversationEngine :: The uuid is found " + uuid);
  +						dkInfo = new DerivedKeyInfo(dkToken);
  +						dkcbHandler.addDerivedKey(uuid, dkInfo);
  +					} else { ///i.e. dkToken has a STR
  +						SecurityTokenReference str2Base =
  +							dkToken.getSecuityTokenReference();
  +						if (str2Base.containsReference()) {
  +							Reference ref2Base = str2Base.getReference();
  +                          //TODO:: Find where can I find the constants.
  +							if (ref2Base
  +								.getValueType()
  +								.equals("http://docs.oasis-open.org/wss/2004/XX/oasis-2004XX-wss-saml-token-profile-1.0#SAMLAssertionID")) {
  +								/* ok now I have a SAML token. What should I do ?
  +								 * -Decrypt the secret.
  +								 * -create tempUUID
  +								 * -add the scTInfo into dkcbHandler
  +								 * -add the derived key token to dkcbHandler.
  +								 */
  +								uuid = ref2Base.getURI();
  +								if(dkcbHandler.getSession(uuid)==null){	 
  +									byte[] key = handleSAML(docSig, uuid);
  +									System.out.println("I am here :-)");
  +									SecurityContextInfo sctInfo =
  +									new SecurityContextInfo(
  +										uuid,
  +										key,
  +										1);
  +									dkcbHandler.addSecurtiyContext(
  +										uuid,
  +									sctInfo);
  +								}		
  +									dkInfo = new DerivedKeyInfo(dkToken);
  +									dkcbHandler.addDerivedKey(uuid, dkInfo);
  +								}					
  +						} else if(str2Base.containsKeyIdentifier()){
  +													Element elem = str2Base.getFirstElement();
  +													//.getKeyIdentifier()System.out.println("KeyIdentifier :: He ehee ........");
  +													String value = elem.getAttribute("ValueType");
  +								if("http://docs.oasis-open.org/wss/2004/XX/oasis-2004XX-wss-saml-token-profile-1.0#SAMLAssertionID".equals(value)){
  +									uuid = ((Text)elem.getChildNodes().item(0)).getNodeValue();
  +									if(dkcbHandler.getSession(uuid)==null){	 
  +									   byte[] key = handleSAML(elem.getOwnerDocument(), uuid);
  +									   System.out.println("UUID of SAML is"+uuid);
  +									   SecurityContextInfo sctInfo = new SecurityContextInfo(uuid,key,1);
  +									   dkcbHandler.addSecurtiyContext(uuid,sctInfo);
  +							    }		
  +								dkInfo = new DerivedKeyInfo(dkToken);
  +								dkcbHandler.addDerivedKey(uuid, dkInfo);
  +								}
  +	                        
  +						} else {
  +							throw new ConversationException("Don't know how to process here");
  +						}
  +						
  +					}		
                   //String uuid = "aNewUuid";
                   String dkId = dkToken.getID();
                   userName = ConversationUtil.generateIdentifier(uuid, dkId);
                   convResult =
  -                        new ConvEngineResult(ConvEngineResult.SIGN_DERIVED_KEY);
  -
  -                try {
  +                    new ConvEngineResult(ConvEngineResult.SIGN_DERIVED_KEY);
                       dkcbHandler.addDerivedKey(uuid, dkInfo);
  -                    log.debug("ConversationEngine: added for signature varification. uuil:"
  +                    log.debug(
  +                        "ConversationEngine: added for signature varification. uuil:"
                               + uuid
                               + " id:"
                               + dkId);
                   } catch (ConversationException e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
  -                }
  +                //TODO :: Ask ruchith to throw correct exception    
  +				} catch (WSSecurityException e2) {
  +					// TODO Auto-generated catch block
  +					e2.printStackTrace();
  +				} 
  +
   
               } else if (el.equals(SCT_TOKEN)) {
  -                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                        "SCT is not Yet supported",
  -                        new Object[]{el.toString()});
  +                throw new WSSecurityException(
  +                    WSSecurityException.INVALID_SECURITY,
  +                    "SCT is not Yet supported",
  +                    new Object[] { el.toString()});
               } else {
  -                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                        "unsupportedToken",
  -                        new Object[]{el.toString()});
  +                throw new WSSecurityException(
  +                    WSSecurityException.INVALID_SECURITY,
  +                    "unsupportedToken",
  +                    new Object[] { el.toString()});
               }
   
               if (tlog.isDebugEnabled()) {
  @@ -664,31 +862,37 @@
               try {
                   // get the key from the callback handler
                   WSPasswordCallback callbacks[] =
  -                        {
  -                            new WSPasswordCallback(userName,
  -                                    WSPasswordCallback.UNKNOWN)};
  +                    {
  +                         new WSPasswordCallback(
  +                            userName,
  +                            WSPasswordCallback.UNKNOWN)};
                   try {
                       dkcbHandler.handle(callbacks);
                   } catch (UnsupportedCallbackException e) {
                       e.printStackTrace();
  -                    throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
  -                            "password call back failed",
  -                            new Object[]{e.toString()});
  +                    throw new WSSecurityException(
  +                        WSSecurityException.FAILED_SIGNATURE,
  +                        "password call back failed",
  +                        new Object[] { e.toString()});
                   } // get the key and check whether it is null
                   byte[] keyBytes = callbacks[0].getKey();
                   if (keyBytes == null) {
  -                    throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
  -                            "password call bac in DerivedKeyTokenHandler failed");
  +                    throw new WSSecurityException(
  +                        WSSecurityException.INVALID_SECURITY,
  +                        "password call bac in DerivedKeyTokenHandler failed");
                   }
   
                   convResult.setKeyAssociated(keyBytes);
  +                //System.out.println(new String(keyBytes));
                   SecretKey symetricKey =
  -                        new SecretKeySpec(keyBytes,
  -                                XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
  +                    new SecretKeySpec(
  +                        keyBytes,
  +                        XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
                   if (sig.checkSignatureValue(symetricKey)) {
                       if (tlog.isDebugEnabled()) {
                           t2 = System.currentTimeMillis();
  -                        tlog.debug("Verify: total= "
  +                        tlog.debug(
  +                            "Verify: total= "
                                   + (t2 - t0)
                                   + ", Find-the token refernced by wsse:Reference= "
                                   + (t1 - t0)
  @@ -697,7 +901,8 @@
                       }
   
                   } else {
  -                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
  +                    throw new WSSecurityException(
  +                        WSSecurityException.FAILED_CHECK);
                   }
               } catch (XMLSignatureException e1) {
                   throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
  @@ -715,19 +920,20 @@
        * @return
        * @throws WSSecurityException
        */
  -    private String getEncAlgo(Node encBodyData)
  -            throws WSSecurityException {
  +    private String getEncAlgo(Node encBodyData) throws WSSecurityException {
           Element tmpE =
  -                (Element) WSSecurityUtil.findElement(encBodyData,
  -                        "EncryptionMethod",
  -                        WSConstants.ENC_NS);
  +            (Element) WSSecurityUtil.findElement(
  +                encBodyData,
  +                "EncryptionMethod",
  +                WSConstants.ENC_NS);
           String symEncAlgo = null;
           if (tmpE != null) {
               symEncAlgo = tmpE.getAttribute("Algorithm");
           }
           if (symEncAlgo == null) {
  -            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM,
  -                    "noEncAlgo");
  +            throw new WSSecurityException(
  +                WSSecurityException.UNSUPPORTED_ALGORITHM,
  +                "noEncAlgo");
           }
           if (doDebug) {
               log.debug("Sym Enc Algo: " + symEncAlgo);
  @@ -735,10 +941,102 @@
           return symEncAlgo;
       } //TODO :: Remove this. Temporary method.
   
  -    private Crypto loadEncryptionCrypto() {
  -        Crypto crypto = null;
  -        String encPropFile = "crypto.properties";
  -        crypto = CryptoFactory.getInstance(encPropFile);
  -        return crypto;
  +   
  +	private Crypto loadDecryptionCrypto() {
  +			Crypto crypto = null;
  +			String encPropFile = (String)configurator.get(WSHandlerConstants.DEC_PROP_FILE);
  +			crypto = CryptoFactory.getInstance(encPropFile);
  +			return crypto;
  +		}
  +    
  +    /**
  +     * This method will be scrapped after the re-architecture.
  +     * Not so elegant work-around.
  +     *
  +     */
  +    private byte[] handleSAML(Document doc, String assertionId) throws ConversationException{
  +    	
  +    	try {
  +            Crypto crypto = this.loadDecryptionCrypto();
  +            //get the security header block
  +            //get the saml assertion
  +            
  +            Element ele=WSSecurityUtil.findWsseSecurityHeaderBlock(WSSConfig.getDefaultWSConfig(), doc, doc.getDocumentElement(), false);
  +            Element samEle =(Element)WSSecurityUtil.getDirectChild(ele, "Assertion", "urn:oasis:names:tc:SAML:1.0:assertion" );
  +//            SAMLAssertion assertion = new SAMLAssertion(samEle);
  +//            
  +//            Iterator itr = assertion.getStatements();
  +//            
  +//           	SAMLAuthenticationStatement auth = (SAMLAuthenticationStatement)itr.next();
  +//           	Element eleEnc = auth.getSubject().getConfirmationData();
  +//            
  +
  +			Element eleEnc = (Element)samEle.getElementsByTagNameNS("http://www.w3.org/2001/04/xmlenc#","EncryptedKey").item(0);
  +            String cb = (String)this.configurator.get(WSHandlerConstants.PW_CALLBACK_CLASS);
  +            
  +            CallbackHandler cbHandler = null;
  +			if (cb != null) {
  +				Class cbClass = null;
  +					try {
  +						cbClass = java.lang.Class.forName(cb);
  +				         cbHandler = (CallbackHandler) cbClass.newInstance();
  +                        
  +					} catch (ClassNotFoundException e) {
  +						throw new ConversationException("Cannot find passwordcallback");
  +					} catch (InstantiationException e2) {
  +						// TODO Auto-generated catch block
  +						e2.printStackTrace();
  +				  	} catch (IllegalAccessException e2) {
  +						// TODO Auto-generated catch block
  +						e2.printStackTrace();
  +					}
  +				
  +			}else{
  +				throw new ConversationException("Cannot find passwordcallback");
  +			}
  +            
  +            WSSecurityEngine eng = new WSSecurityEngine();
  +            eng.handleEncryptedKey(eleEnc, cbHandler, crypto);	
  +            byte[] key = eng.getDecryptedBytes();    
  +            
  +            return key;
  +            
  +    	}catch (WSSecurityException e1) {
  +			// TODO Auto-generated catch block
  +			e1.printStackTrace();
  +			throw new ConversationException("Cannot find passwordcallback");
  +		}
  +    	
  +    	   	
  +    
  +    
  +    }
  +    /** 
  +     * Taken from WSSecurity Engine
  +     * @param encBodyData
  +     * @return
  +     */
  +    private boolean isContent(Node encBodyData) {
  +        /*
  +         * Depending on the encrypted data type (Content or Element) the encBodyData either
  +         * holds the element whose contents where encrypted, e.g. soapenv:Body, or the
  +         * xenc:EncryptedData element (in case of Element encryption). In either case we need
  +         * to get the xenc:EncryptedData element. So get it. The findElement method returns
  +         * immediatly if its already the correct element.
  +         * Then we can get the Type attribute.
  +         */
  +
  +        Element tmpE = (Element) WSSecurityUtil.findElement(encBodyData,
  +                "EncryptedData", WSConstants.ENC_NS);
  +        String typeStr = null;
  +        boolean content = true;
  +        if (tmpE != null) {
  +            typeStr = tmpE.getAttribute("Type");
  +        }
  +        if (typeStr != null) {
  +            content = typeStr.equals(WSConstants.ENC_NS + "Content") ? true : false;
  +        }
  +        return content;
       }
  +    
   }
  
  
  
  1.3       +2 -2      ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyTokenAdder.java
  
  Index: DerivedKeyTokenAdder.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyTokenAdder.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- DerivedKeyTokenAdder.java	9 Aug 2004 17:53:43 -0000	1.2
  +++ DerivedKeyTokenAdder.java	16 Oct 2004 06:06:53 -0000	1.3
  @@ -40,8 +40,8 @@
   
           // log.debug("Begin add username token...");
           Element securityHeader = insertSecurityHeader(doc);
  -        WSSecurityUtil.appendChildElement(doc, securityHeader,
  -                dkToken.getElement());
  +        WSSecurityUtil.prependChildElement(doc, securityHeader,
  +                dkToken.getElement(),false);
           return doc;
       }
   }
  
  
  
  1.5       +33 -0     ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationSession.java
  
  Index: ConversationSession.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationSession.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- ConversationSession.java	9 Aug 2004 17:53:43 -0000	1.4
  +++ ConversationSession.java	16 Oct 2004 06:06:53 -0000	1.5
  @@ -21,6 +21,7 @@
   import org.apache.commons.logging.LogFactory;
   import org.apache.ws.security.conversation.message.info.DerivedKeyInfo;
   import org.apache.ws.security.conversation.message.info.SecurityContextInfo;
  +import org.apache.ws.security.message.token.Reference;
   
   import java.util.Hashtable;
   
  @@ -63,6 +64,10 @@
        * Last time the session was used/modified
        */
       private long lastTouched;
  +    
  +    private boolean addBase2Message = true;
  +    
  +    private Reference ref2Base = null;
   
       /**
        * Creates a new conversation session for a gien security context
  @@ -158,6 +163,34 @@
        */
       public long getLastTouched() {
           return this.lastTouched;
  +    }
  +
  +    /**
  +     * @return
  +     */
  +    public boolean isAddBase2Message() {
  +        return addBase2Message;
  +    }
  +
  +    /**
  +     * @return
  +     */
  +    public Reference getRef2Base() {
  +        return ref2Base;
  +    }
  +
  +    /**
  +     * @param b
  +     */
  +    public void setAddBase2Message(boolean b) {
  +        addBase2Message = b;
  +    }
  +
  +    /**
  +     * @param reference
  +     */
  +    public void setRef2Base(Reference reference) {
  +        ref2Base = reference;
       }
   
   }
  
  
  
  1.5       +46 -42    ws-fx/wss4j/src/org/apache/ws/security/conversation/KeyDerivator.java
  
  Index: KeyDerivator.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/KeyDerivator.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- KeyDerivator.java	9 Aug 2004 17:53:43 -0000	1.4
  +++ KeyDerivator.java	16 Oct 2004 06:06:53 -0000	1.5
  @@ -70,46 +70,46 @@
           DerivedKeyInfo dkInfo = (DerivedKeyInfo) convSession.getDerivedKeys().get(derivedKeyTokenId);
           SecurityTokenReference secTokRef = dkInfo.getSecurityTokenReference();
           log.debug("KeyDerivator: deriveKey: security token reference: " + secTokRef);
  -        if (secTokRef != null) {
  -            if (secTokRef.toString().equals("<wsse:SecurityTokenReference/>")) {//No security token reference
  -                log.debug("KeyDerivator: deriveKey: No security token refernece available");
  -                return deriveTokenFromContext(convSession, dkInfo);
  -            } else {
  -                String contextIdentifier = convSession.getContextInfo().getIdentifier();
  -
  -                String wsuId = secTokRef.getReference().getURI();
  -
  -                Element sctEle = WSSecurityUtil.getElementByWsuId(WSSConfig.getDefaultWSConfig(), secTokRef.getElement().getOwnerDocument(), wsuId);
  -
  -                try {
  -                    SecurityContextToken sct = new SecurityContextToken(sctEle);
  -                    if (contextIdentifier.equals(sct.getIdentifier()))
  -                        return deriveTokenFromContext(convSession, dkInfo);
  -                    else
  -                        throw new ConversationException("Derivation source cannot be determined");
  -                } catch (WSSecurityException secEx) {
  -                    /** @todo Supporting other tokens other than SCT as the derivation source */
  -                    //Here we should check whether it is some other type of a token
  -                    //E.g. DerivedKeyToken
  -                }
  -
  -                if (secTokRef.getReference().getURI().equals(contextIdentifier)) { //If the reference is to the SecurityContextToken
  -                    return deriveTokenFromContext(convSession, dkInfo);
  -                } else {
  -                    //Derive from some other security token other than the relevent security context
  -                    /** @todo Derive from some other security token other than the relevent security context
  -                     * For example this can be another DerivedKeyToken
  -                     * */
  -                    throw new ConversationException("KeyDerivator:  Deriving from some " +
  -                            "other security token other than the " +
  -                            "relevent security context: Not implemented :-(");
  -
  -                }
  -            }
  -        } else { //There is no SecurityTokenRefernece
  +//        if (secTokRef != null) {
  +//            if (secTokRef.toString().equals("<wsse:SecurityTokenReference/>")) {//No security token reference
  +//                log.debug("KeyDerivator: deriveKey: No security token refernece available");
  +//                return deriveTokenFromContext(convSession, dkInfo);
  +//            } else {
  +//                String contextIdentifier = convSession.getContextInfo().getIdentifier();
  +//
  +//                String wsuId = secTokRef.getReference().getURI();
  +//
  +//                Element sctEle = WSSecurityUtil.getElementByWsuId(WSSConfig.getDefaultWSConfig(), secTokRef.getElement().getOwnerDocument(), wsuId);
  +//
  +//                try {
  +//                    SecurityContextToken sct = new SecurityContextToken(sctEle);
  +//                    if (contextIdentifier.equals(sct.getIdentifier()))
  +//                        return deriveTokenFromContext(convSession, dkInfo);
  +//                    else
  +//                        throw new ConversationException("Derivation source cannot be determined");
  +//                } catch (WSSecurityException secEx) {
  +//                    /** @todo Supporting other tokens other than SCT as the derivation source */
  +//                    //Here we should check whether it is some other type of a token
  +//                    //E.g. DerivedKeyToken
  +//                }
  +//
  +//                if (secTokRef.getReference().getURI().equals(contextIdentifier)) { //If the reference is to the SecurityContextToken
  +//                    return deriveTokenFromContext(convSession, dkInfo);
  +//                } else {
  +//                    //Derive from some other security token other than the relevent security context
  +//                    /** @todo Derive from some other security token other than the relevent security context
  +//                     * For example this can be another DerivedKeyToken
  +//                     * */
  +//                    throw new ConversationException("KeyDerivator:  Deriving from some " +
  +//                            "other security token other than the " +
  +//                            "relevent security context: Not implemented :-(");
  +//
  +//                }
  +//            }
  +//        } else { //There is no SecurityTokenRefernece
               log.debug("KeyDerivator: deriveKey: No security token refernece available");
               return deriveTokenFromContext(convSession, dkInfo);
  -        }
  +  //      }
   
       }
   
  @@ -198,11 +198,15 @@
                       "Generation : " + generation +
                       "Offset : " + offset);
           } else if (convSession.getKeyLength() != -1) { //Session is configured to use fixed size keys
  -            if (generation == -1)
  -                throw new ConversationException("Generation value is not avaliable (fixed size keys are used: " +
  -                        "Key size : " + convSession.getKeyLength() + ")");
  -            else
  +            if (generation == -1){
  +          		log.debug("Generation set to zero");
  +          		generation = 0;   
  +          return (int)convSession.getKeyLength() * generation;
  +//                throw new ConversationException("Generation value is not avaliable (fixed size keys are used: " +
  +//                        "Key size : " + convSession.getKeyLength() + ")");
  +            }else{
                   return (int) convSession.getKeyLength() * generation;
  +            }    
           } else if (offset != -1) { //Fixed size keys are NOT used: The length and offset values should be available in the DKT
               return offset;
           } else if (generation != -1) { //Here length should be specified in the DKT
  
  
  
  1.7       +12 -1     ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyCallbackHandler.java
  
  Index: DerivedKeyCallbackHandler.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/DerivedKeyCallbackHandler.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- DerivedKeyCallbackHandler.java	9 Aug 2004 17:53:43 -0000	1.6
  +++ DerivedKeyCallbackHandler.java	16 Oct 2004 06:06:53 -0000	1.7
  @@ -95,6 +95,16 @@
           }
   
       }
  +    
  +    public static ConversationSession getSession(String uuid) throws ConversationException{
  +		ConversationSession session = (ConversationSession) conversationSessionTable.get(uuid);
  +				if (session != null) {
  +					return session;
  +				} else {
  +					return null;
  +				}
  +
  +    }
   
       /**
        * If the Label element is not available in a DerivedKeyToken element then
  @@ -116,7 +126,8 @@
               throw new ConversationException("The key size cannot be set: No such context/session");
           }
       }
  -
  +    
  +   
       /**
        * Adds a derived key into a session identified by the uuid
        *
  
  
  
  1.7       +54 -38    ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationManager.java
  
  Index: ConversationManager.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/ConversationManager.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- ConversationManager.java	11 Aug 2004 06:04:05 -0000	1.6
  +++ ConversationManager.java	16 Oct 2004 06:06:53 -0000	1.7
  @@ -70,19 +70,19 @@
       protected String canonAlgo = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
   
       /**
  -     * 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 DerivedKeyInfo addDerivedKeyToken(Document doc,
  +      * Adds Derived key tokens to the header of the SOAP message, given the
  +      * following parameters.
  +      * @param doc
  +      * @param uuid
  +      * @param dkcbHandler
  +      * @param stRef2Base -SecurityTOkenReference to the token, from which the derived
  +      *                    key is derived from
  +      * @return
  +      * @throws ConversationException
  +      */
  +     public DerivedKeyInfo createDerivedKeyToken(Document doc,
                                                String uuid,
  -                                             DerivedKeyCallbackHandler dkcbHandler)
  +                                             DerivedKeyCallbackHandler dkcbHandler,SecurityTokenReference stRef2Base, int keyLen )
               throws ConversationException {
           String genID = ConversationUtil.genericID();
           
  @@ -90,10 +90,10 @@
            * This metod is 4-step procedure. 
            */
            
  -        // step 1 : Creating wsse:Reference
  +        // step 1 : Creating wsse:Reference to DerivedKeyToken
           Reference ref = new Reference(WSSConfig.getDefaultWSConfig(), doc);
           ref.setURI("#" + genID);
  -        ref.setValueType("DerivedKeyToken");
  +        ref.setValueType("http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk");
           SecurityTokenReference stRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc);
           stRef.setReference(ref);
   
  @@ -103,16 +103,18 @@
   
           // step 2 :Create the DerriveToken
           DerivedKeyToken dtoken = new DerivedKeyToken(doc);
  -        dtoken.setLabel(doc, "WSSecureConversationWSSecureConversation");
  -        dtoken.setNonce(doc, "nonce.....");
  +		if(stRef2Base != null){
  +			dtoken.setSecuityTokenReference(doc, stRef2Base);
  +		}
  +        dtoken.setLabel(doc, "WS-SecureConversationWS-SecureConversation");
  +        dtoken.setNonce(doc, ConversationUtil.generateNonce(128));
           dtoken.setID(genID);
  -
  -        if (dkcbHandler.getDerivedKeyLength(uuid) == -1) {
  -            //key legnth is varing
  -        } else {
  -            dtoken.setGeneration(doc, this.generation);
  -        }
  -
  +		//System.out.println("Fix me here ....");
  +		
  +		if(keyLen!=-1){
  +		   dtoken.setLength(doc,keyLen);
  +		}
  +        
           //step 3 :add the derived key token infomation into the dkcbHandler
           DerivedKeyInfo dkInfo = null;
           try {
  @@ -124,12 +126,16 @@
               throw new ConversationException("ConversationManager:: Cannot add Derived key token to the envelope");
           }
   
  -        //step 4 : add the token to the soap message
  -        DerivedKeyTokenAdder adder = new DerivedKeyTokenAdder();
  -        adder.build(doc, dtoken);
  -        return dkInfo;
  +               
  +		return dkInfo;
   
       }
  +    
  +    
  +    public void addDkToken(Document doc, DerivedKeyInfo info){
  +    	  DerivedKeyTokenAdder adder = new DerivedKeyTokenAdder();
  +    	  adder.build(doc, info.getDkTok());
  +    }		  
   
       /**
        * Manages derived key encryption.
  @@ -138,7 +144,7 @@
        * @param actor
        * @param mu
        * @param doc
  -     * @param secRef
  +     * @param secRef - SecurityTokenReference pointing to the derived Key
        * @param dkcbHandler
        * @throws ConversationException
        */
  @@ -147,7 +153,8 @@
                                  boolean mu,
                                  Document doc,
                                  SecurityTokenReference secRef,
  -                               DerivedKeyCallbackHandler dkcbHandler)
  +                               DerivedKeyCallbackHandler dkcbHandler, Vector parts,
  +                               String symAlgo)
               throws ConversationException {
           WSEncryptBody wsEncrypt = new WSEncryptBody(actor, mu);
   
  @@ -156,14 +163,14 @@
            * Rest is as same as EMBEDDED_KEYNAME , i.e. we want to encrypt the message
            * using a symmetric key and the result would be an <EncryptedData> element.
            * Steps are
  -         * step 1: Adding SecurityTokenReference to wsEncrypt
  +         * step 1: Adding SecurityTokenReference pointing to DkToken
            * step 2: Adding the key into wsEncrypt
            * step 3: Setting the user.
            */
           wsEncrypt.setKeyIdentifierType(WSConstants.EMBED_SECURITY_TOKEN_REF);
  -
  +		
           /*
  -         * step 1: Adding SecurityTokenReference.
  +         * step 1: Adding SecurityTokenReference pointing to DkToken.
            */
           wsEncrypt.setSecurityTokenReference(secRef);
   
  @@ -187,10 +194,18 @@
            * step 3: set the user.
            */
           wsEncrypt.setUserInfo(encUser);
  -
  +        
  +        /*
  +         * step 4 : Setting encryption parts
  +         */
  +         wsEncrypt.setParts(parts);  
  +        
  +         wsEncrypt.setSymmetricEncAlgorithm(symAlgo);
  +         
           try {
               wsEncrypt.build(doc, null);
           } catch (WSSecurityException e) {
  +        	e.printStackTrace();
               throw new ConversationException("ConversationManager :: Encryption: error during message processing");
           }
   
  @@ -208,7 +223,7 @@
       public void performDK_Sign(Document doc,
                                  DerivedKeyCallbackHandler dkcbHandler,
                                  String uuid,
  -                               DerivedKeyInfo dkSigInfo)
  +                               DerivedKeyInfo dkSigInfo, Vector parts)
               throws ConversationException {
           //            Signing....
           //        HMAC_SignVerify sign = new HMAC_SignVerify();
  @@ -216,6 +231,7 @@
   
           String sigUser =
                   ConversationUtil.generateIdentifier(uuid, dkSigInfo.getId());
  +        System.out.println("Signature user is ::"+sigUser);
           WSPasswordCallback pwCb =
                   new WSPasswordCallback(sigUser, WSPasswordCallback.UNKNOWN);
           Callback[] callbacks = new Callback[1];
  @@ -228,7 +244,7 @@
           }
           try {
               Reference ref = dkSigInfo.getSecTokRef2DkToken().getReference();
  -            this.build(doc, ref, pwCb.getKey(), null);
  +            this.build(doc, ref, pwCb.getKey(), parts);
           } catch (WSSecurityException e1) {
               e1.printStackTrace();
               throw new ConversationException("ConversationManager :: Error performing signature.");
  @@ -268,6 +284,7 @@
                       new Object[]{"For symmeric key signatures - Reference object must be provided"});
           }
           String sigAlgo = XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
  +        log.debug("Key is "+new String(sk));
   
           SecretKey sharedKey = new SecretKeySpec(sk, sigAlgo);
   
  @@ -379,10 +396,9 @@
            * -Append the signature element.
            * -Apped the KeyInfo element
            */
  -        WSSecurityUtil.prependChildElement(doc,
  +        WSSecurityUtil.appendChildElement(doc,
                   securityHeader,
  -                sig.getElement(),
  -                false);
  +                sig.getElement());
   
           /*
            * Put the "Reference object" into secRef in KeyInfo
  
  
  
  1.5       +11 -0     ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/SecurityContextInfo.java
  
  Index: SecurityContextInfo.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/SecurityContextInfo.java,v
  retrieving revision 1.4
  retrieving revision 1.5
  diff -u -r1.4 -r1.5
  --- SecurityContextInfo.java	9 Aug 2004 17:53:44 -0000	1.4
  +++ SecurityContextInfo.java	16 Oct 2004 06:06:54 -0000	1.5
  @@ -81,7 +81,18 @@
           this.frequency = frequency; // frequency of refreshing the derrived key
           /** @todo get the values of other elements (any elements) of SCT*/
       }
  +    
  +    
  +	public SecurityContextInfo(String uuid,
  +								   byte[] sharedSecret,
  +								   int frequency) throws WSSecurityException {
   
  +			this.sharedSecret = sharedSecret;
  +			this.identifier = uuid;
  +			this.frequency = frequency; // frequency of refreshing the derrived key
  +			/** @todo get the values of other elements (any elements) of SCT*/
  +	}
  +     
       /**
        * @return
        */
  
  
  
  1.6       +16 -0     ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/DerivedKeyInfo.java
  
  Index: DerivedKeyInfo.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/message/info/DerivedKeyInfo.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- DerivedKeyInfo.java	9 Aug 2004 18:02:47 -0000	1.5
  +++ DerivedKeyInfo.java	16 Oct 2004 06:06:54 -0000	1.6
  @@ -45,8 +45,10 @@
       private int usageCount;
       private SecurityTokenReference secTokenRef;
       private SecurityTokenReference secTokRef2DkToken;
  +    private DerivedKeyToken dkTok = null;
   
       public DerivedKeyInfo(DerivedKeyToken dkt) throws WSSecurityException {
  +    	this.dkTok=dkt;
           this.properties = dkt.getProperties();
           this.generation = dkt.getGeneration();
           this.offset = dkt.getOffset();
  @@ -107,4 +109,18 @@
       public SecurityTokenReference getSecTokRef2DkToken() {
           return secTokRef2DkToken;
       }
  +    /**
  +     * @return
  +     */
  +    public DerivedKeyToken getDkTok() {
  +        return dkTok;
  +    }
  +
  +    /**
  +     * @param token
  +     */
  +    public void setDkTok(DerivedKeyToken token) {
  +        dkTok = token;
  +    }
  +
   }
  
  
  
  1.6       +1 -1      ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestSecurityTokenResponse.java
  
  Index: RequestSecurityTokenResponse.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestSecurityTokenResponse.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- RequestSecurityTokenResponse.java	9 Aug 2004 18:02:47 -0000	1.5
  +++ RequestSecurityTokenResponse.java	16 Oct 2004 06:06:54 -0000	1.6
  @@ -101,7 +101,7 @@
                       new Object[]{el});
           }
   
  -        //System.out.println("RequestSecurityTokenResponse created");
  +       
   
       }
   
  
  
  
  1.7       +3 -1      ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/DerivedKeyToken.java
  
  Index: DerivedKeyToken.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/DerivedKeyToken.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- DerivedKeyToken.java	9 Aug 2004 17:53:44 -0000	1.6
  +++ DerivedKeyToken.java	16 Oct 2004 06:06:54 -0000	1.7
  @@ -129,7 +129,9 @@
        * @param ref Security token reference
        */
       public void setSecuityTokenReference(Document doc, SecurityTokenReference ref) {
  -        WSSecurityUtil.appendChildElement(doc, this.element, ref.getElement());
  +        this.elementSecurityTokenReference = ref.getElement();
  +        //WSSecurityUtil.appendChildElement(doc, this.element, ref.getElement());
  +        this.element.appendChild(ref.getElement());
       }
   
       /**
  
  
  
  1.6       +1 -1      ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestedProofToken.java
  
  Index: RequestedProofToken.java
  ===================================================================
  RCS file: /home/cvs/ws-fx/wss4j/src/org/apache/ws/security/conversation/message/token/RequestedProofToken.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- RequestedProofToken.java	9 Aug 2004 17:53:44 -0000	1.5
  +++ RequestedProofToken.java	16 Oct 2004 06:06:54 -0000	1.6
  @@ -134,7 +134,7 @@
               } catch (java.lang.Exception e) {
                   throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
                           "RequestedProofToken: cannot create instance of password callback: "
  -                        + callback);
  +                        + callback +":: ErrMsg "+e.getMessage());
               }
               secEngine.handleEncryptedKey((Element) ndList.item(0),
                       cbHandler,