You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-commits@axis.apache.org by am...@apache.org on 2012/03/01 10:54:07 UTC

svn commit: r1295489 [2/5] - in /axis/axis2/java/rampart/branches/1_6: ./ modules/rampart-core/src/main/java/org/apache/rampart/ modules/rampart-core/src/main/java/org/apache/rampart/builder/ modules/rampart-core/src/main/java/org/apache/rampart/handle...

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/AsymmetricBindingBuilder.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/AsymmetricBindingBuilder.java?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/AsymmetricBindingBuilder.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/AsymmetricBindingBuilder.java Thu Mar  1 09:54:05 2012
@@ -34,9 +34,11 @@ import org.apache.ws.secpolicy.model.Tok
 import org.apache.ws.secpolicy.model.X509Token;
 import org.apache.ws.security.WSConstants;
 import org.apache.ws.security.WSEncryptionPart;
+import org.apache.ws.security.WSSConfig;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.conversation.ConversationException;
 import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.handler.WSHandlerResult;
 import org.apache.ws.security.message.WSSecDKEncrypt;
 import org.apache.ws.security.message.WSSecDKSign;
 import org.apache.ws.security.message.WSSecEncrypt;
@@ -45,18 +47,13 @@ import org.apache.ws.security.message.WS
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Vector;
+import javax.xml.crypto.dsig.Reference;
+import java.util.*;
 
 public class AsymmetricBindingBuilder extends BindingBuilder {
 
     private static Log log = LogFactory.getLog(AsymmetricBindingBuilder.class);
-    private static Log tlog = LogFactory.getLog(RampartConstants.TIME_LOG);	
-
-    private Token sigToken;
-
-    private WSSecSignature sig;
+    private static Log tlog = LogFactory.getLog(RampartConstants.TIME_LOG);
 
     private WSSecEncryptedKey encrKey;
     
@@ -64,7 +61,7 @@ public class AsymmetricBindingBuilder ex
     
     private byte[] encryptedKeyValue;
 
-    private Vector signatureValues = new Vector();
+    private List<byte[]> signatureValues = new ArrayList<byte[]>();
 
     private Element encrTokenElement;
     
@@ -72,9 +69,12 @@ public class AsymmetricBindingBuilder ex
     
     private Element encrDKTElement;
 
-    private Vector sigParts = new Vector();
+    private List<WSEncryptionPart> sigParts = new ArrayList<WSEncryptionPart>();
     
-    private Element signatureElement; 
+    private Element signatureElement;
+
+    private Element refList;
+
     
     public void build(RampartMessageData rmd) throws RampartException {
         log.debug("AsymmetricBindingBuilder build invoked");
@@ -84,7 +84,7 @@ public class AsymmetricBindingBuilder ex
             this.addTimestamp(rmd);
         }
 
-        if (SPConstants.ENCRYPT_BEFORE_SIGNING.equals(rpd.getProtectionOrder())) {
+        if (RampartUtil.encryptFirst(rpd)) {
             this.doEncryptBeforeSig(rmd);
         } else {
             this.doSignBeforeEncrypt(rmd);
@@ -110,7 +110,7 @@ public class AsymmetricBindingBuilder ex
          */
         Element encrDKTokenElem = null;
         WSSecEncrypt encr = null;
-        Element refList = null;
+        refList = null;
         WSSecDKEncrypt dkEncr = null;
 
         /*
@@ -122,7 +122,7 @@ public class AsymmetricBindingBuilder ex
         } else {
             encryptionToken = rpd.getInitiatorToken();
         }
-        Vector encrParts = RampartUtil.getEncryptedParts(rmd);
+        List<WSEncryptionPart> encrParts = RampartUtil.getEncryptedParts(rmd);
         
         //Signed parts are determined before encryption because encrypted signed  headers
         //will not be included otherwise
@@ -190,16 +190,18 @@ public class AsymmetricBindingBuilder ex
                 }
             }
 
-            RampartUtil.appendChildToSecHeader(rmd, refList);
+            refList = RampartUtil.appendChildToSecHeader(rmd, refList);
             
             if(tlog.isDebugEnabled()){
             	t1 = System.currentTimeMillis();
             }
-            
+
             this.setInsertionLocation(encrTokenElement);
 
             RampartUtil.handleEncryptedSignedHeaders(encrParts, this.sigParts, doc);
-            
+
+            // TODO may contain deifferent types of objects as values, therefore cannot use strongly type maps
+            // need to figure out a way
             HashMap sigSuppTokMap = null;
             HashMap endSuppTokMap = null;
             HashMap sgndEndSuppTokMap = null;
@@ -208,8 +210,8 @@ public class AsymmetricBindingBuilder ex
             HashMap sgndEndEncSuppTokMap = null;
             
             if(this.timestampElement != null){
-            	sigParts.add(new WSEncryptionPart(RampartUtil
-                    .addWsuIdToElement((OMElement) this.timestampElement)));
+            	sigParts.add(RampartUtil.createEncryptionPart(WSConstants.TIMESTAMP_TOKEN_LN,
+                            RampartUtil.addWsuIdToElement((OMElement) this.timestampElement)));
             }
             
             if (rmd.isInitiator()) {
@@ -233,9 +235,9 @@ public class AsymmetricBindingBuilder ex
                 SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();           
                 sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
                 
-                Vector supportingToks = rpd.getSupportingTokensList();
-                for (int i = 0; i < supportingToks.size(); i++) {
-                    this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
+                List<SupportingToken> supportingToks = rpd.getSupportingTokensList();
+                for (SupportingToken supportingTok : supportingToks) {
+                    this.handleSupportingTokens(rmd, supportingTok);
                 } 
                 
                 SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
@@ -258,21 +260,23 @@ public class AsymmetricBindingBuilder ex
             }
 
             if (rmd.isInitiator()) {
-                
-                endSuppTokMap.putAll(endEncSuppTokMap);
+
+                if (endSuppTokMap != null) {
+                    endSuppTokMap.putAll(endEncSuppTokMap);
+                }
                 // Do endorsed signatures
-                Vector endSigVals = this.doEndorsedSignatures(rmd,
+                List<byte[]> endSigVals = this.doEndorsedSignatures(rmd,
                         endSuppTokMap);
-                for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
-                    signatureValues.add(iter.next());
+                for (byte[] endSigVal : endSigVals) {
+                    signatureValues.add(endSigVal);
                 }
 
                 sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
                 // Do signed endorsing signatures
-                Vector sigEndSigVals = this.doEndorsedSignatures(rmd,
+                List<byte[]> sigEndSigVals = this.doEndorsedSignatures(rmd,
                         sgndEndSuppTokMap);
-                for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
-                    signatureValues.add(iter.next());
+                for (byte[] sigEndSigVal : sigEndSigVals) {
+                    signatureValues.add(sigEndSigVal);
                 }
             }
             
@@ -288,15 +292,16 @@ public class AsymmetricBindingBuilder ex
             	if(tlog.isDebugEnabled()){
             		t3 = System.currentTimeMillis();
             	}
-                Vector secondEncrParts = new Vector();
+
+                List<WSEncryptionPart> secondEncrParts = new ArrayList<WSEncryptionPart>();
 
                 // Now encrypt the signature using the above token
                 secondEncrParts.add(new WSEncryptionPart(this.mainSigId,
                         "Element"));
                 
                 if(rmd.isInitiator()) {
-                    for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
-                        secondEncrParts.add(new WSEncryptionPart((String)encryptedTokensIdList.get(i),"Element"));
+                    for (String anEncryptedTokensIdList : encryptedTokensIdList) {
+                        secondEncrParts.add(new WSEncryptionPart(anEncryptedTokensIdList, "Element"));
                     }
                 }
 
@@ -389,9 +394,9 @@ public class AsymmetricBindingBuilder ex
             SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();           
             sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
             
-            Vector supportingToks = rpd.getSupportingTokensList();
-            for (int i = 0; i < supportingToks.size(); i++) {
-                this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
+            List<SupportingToken> supportingToks = rpd.getSupportingTokensList();
+            for (SupportingToken supportingTok : supportingToks) {
+                this.handleSupportingTokens(rmd, supportingTok);
             } 
             
             SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
@@ -414,19 +419,17 @@ public class AsymmetricBindingBuilder ex
             this.doSignature(rmd);
         }
         
-        Vector supportingToks = rpd.getSupportingPolicyData();
-        for (int i = 0; i < supportingToks.size(); i++) {
-            SupportingPolicyData policyData = null;
-            if (supportingToks.get(i) != null) {
-                policyData = (SupportingPolicyData) supportingToks.get(i);
-                Vector supportingSigParts = RampartUtil.getSupportingSignedParts(rmd,
+        List<SupportingPolicyData> supportingToks = rpd.getSupportingPolicyData();
+        for (SupportingPolicyData policyData : supportingToks) {
+            if (policyData != null) { // TODO do we need this null check ?
+                List<WSEncryptionPart> supportingSigParts = RampartUtil.getSupportingSignedParts(rmd,
                         policyData);
 
                 if (supportingSigParts.size() > 0
                         && ((rmd.isInitiator() && rpd.getInitiatorToken() != null) || (!rmd
-                                .isInitiator() && rpd.getRecipientToken() != null))) {
+                        .isInitiator() && rpd.getRecipientToken() != null))) {
                     // Do signature for policies defined under SupportingToken.
-                    this.doSupportingSignature(rmd, supportingSigParts,policyData);
+                    this.doSupportingSignature(rmd, supportingSigParts, policyData);
                 }
             }
         }
@@ -436,21 +439,25 @@ public class AsymmetricBindingBuilder ex
         if (rmd.isInitiator()) {
             
             // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
-            endSuppTokMap.putAll(endEncSuppTokMap);
+            if (endSuppTokMap != null) {
+                endSuppTokMap.putAll(endEncSuppTokMap);
+            }
             // Do endorsed signatures
-            Vector endSigVals = this.doEndorsedSignatures(rmd,
+            List<byte[]> endSigVals = this.doEndorsedSignatures(rmd,
                     endSuppTokMap);
-            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
-                signatureValues.add(iter.next());
+            for (byte[] endSigVal : endSigVals) {
+                signatureValues.add(endSigVal);
             }
 
             //Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
-            sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
+            if (sgndEndSuppTokMap != null) {
+                sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
+            }
             // Do signed endorsing signatures
-            Vector sigEndSigVals = this.doEndorsedSignatures(rmd,
+            List<byte[]> sigEndSigVals = this.doEndorsedSignatures(rmd,
                     sgndEndSuppTokMap);
-            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
-                signatureValues.add(iter.next());
+            for (byte[] sigEndSigVal : sigEndSigVals) {
+                signatureValues.add(sigEndSigVal);
             }
         }
         
@@ -458,7 +465,7 @@ public class AsymmetricBindingBuilder ex
     		t1 = System.currentTimeMillis();
     	}
              
-        Vector encrParts = RampartUtil.getEncryptedParts(rmd);
+        List<WSEncryptionPart> encrParts = RampartUtil.getEncryptedParts(rmd);
         
         //Check for signature protection
         if(rpd.isSignatureProtection() && this.mainSigId != null) {
@@ -466,8 +473,8 @@ public class AsymmetricBindingBuilder ex
         }
         
         if(rmd.isInitiator()) {
-            for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
-                encrParts.add(new WSEncryptionPart((String)encryptedTokensIdList.get(i),"Element"));
+            for (String anEncryptedTokensIdList : encryptedTokensIdList) {
+                encrParts.add(new WSEncryptionPart(anEncryptedTokensIdList, "Element"));
             }
         }
 
@@ -570,13 +577,11 @@ public class AsymmetricBindingBuilder ex
             }
         }
         
-        Vector supportingTokens = rpd.getSupportingPolicyData();
-        for (int i = 0; i < supportingTokens.size(); i++) {
-            SupportingPolicyData policyData = null;
-            if (supportingTokens.get(i) != null) {
-                policyData = (SupportingPolicyData) supportingTokens.get(i);
+        List<SupportingPolicyData> supportingTokens = rpd.getSupportingPolicyData();
+        for (SupportingPolicyData policyData : supportingTokens) {
+            if (policyData != null) { // TODO do we need this null check ?
                 Token supportingEncrToken = policyData.getEncryptionToken();
-                Vector supoortingEncrParts = RampartUtil.getSupportingEncryptedParts(rmd,
+                List<WSEncryptionPart> supoortingEncrParts = RampartUtil.getSupportingEncryptedParts(rmd,
                         policyData);
 
                 if (supportingEncrToken != null && supoortingEncrParts.size() > 0) {
@@ -594,7 +599,7 @@ public class AsymmetricBindingBuilder ex
         
     }
     
-    private void doSupportingSignature(RampartMessageData rmd, Vector supportingSigParts,
+    private void doSupportingSignature(RampartMessageData rmd, List<WSEncryptionPart> supportingSigParts,
             SupportingPolicyData supportingData) throws RampartException {
 
         Token supportingSigToken;
@@ -624,13 +629,19 @@ public class AsymmetricBindingBuilder ex
         }
 
         try {
-            supportingSig.addReferencesToSign(supportingSigParts, rmd.getSecHeader());
-            supportingSig.computeSignature();
+            supportingSig.setDigestAlgo(rmd.getPolicyData().getAlgorithmSuite().getDigest());
 
-            supportingSignatureElement = supportingSig.getSignatureElement();
+            List<Reference> referenceList
+                    = supportingSig.addReferencesToSign(supportingSigParts, rmd.getSecHeader());
 
-            this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this
-                    .getInsertionLocation(), supportingSignatureElement));
+            /**
+             * Before migration it was - this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this
+             *       .getInsertionLocation(), supportingSignatureElement));
+             *
+             * In this case we need to append <Signature>..</Signature> element to
+             * current insertion location
+             */
+            supportingSig.computeSignature(referenceList, false, this.getInsertionLocation());
 
         } catch (WSSecurityException e) {
             throw new RampartException("errorInSignatureWithX509Token", e);
@@ -654,12 +665,20 @@ public class AsymmetricBindingBuilder ex
         if(tlog.isDebugEnabled()){
     		t0 = System.currentTimeMillis();
     	}
+        Token sigToken;
         if(rmd.isInitiator()) {
             sigToken = rpd.getInitiatorToken();
         } else {
             sigToken = rpd.getRecipientToken();
         }
 
+        /**
+         * Note : It doesn't make sense to use Derived Keys in an Asymmetric binding environment to sign messages.
+         * In asymmetric binding environment we always sign the message using sender's private key. We do *not*
+         * use a session/ephemeral key to sign the message. We always use PKC keys to sign and verify messages.
+         * Therefore we do not need to have following code segment.
+         * TODO Confirm and remove.
+         */
         if (sigToken.isDerivedKeys()) {
             // Set up the encrypted key to use
             if(this.encrKey == null) {
@@ -667,6 +686,7 @@ public class AsymmetricBindingBuilder ex
             }
             
             WSSecDKSign dkSign = new WSSecDKSign();
+
             dkSign.setExternalKey(this.encryptedKeyValue, this.encryptedKeyId);
 
             // Set the algo info
@@ -685,21 +705,46 @@ public class AsymmetricBindingBuilder ex
 
                 dkSign.setParts(sigParts);
 
-                dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
+                List<Reference> referenceList
+                        = dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
 
-                // Do signature
-                dkSign.computeSignature();
+                 /**
+                 * Add <wsc:DerivedKeyToken>..</wsc:DerivedKeyToken> to security
+                 * header. We need to add this just after Encrypted Key and just before <Signature>..</Signature>
+                 * elements. (As a convention)
+                 */
+
+                if (refList == null) {
+                    //dkSign.appendDKElementToHeader(rmd.getSecHeader());
+                    this.sigDKTElement = RampartUtil.insertSiblingAfter(rmd,
+                            this.getInsertionLocation(), dkSign.getdktElement());
+                    this.setInsertionLocation(this.sigDKTElement);
+                     // Do signature
+                    /**
+                     * Create and prepend signature
+                     */
+                    dkSign.computeSignature(referenceList, false, this.getInsertionLocation());
+                } else {
+                    this.sigDKTElement = RampartUtil.insertSiblingBefore(rmd, refList, dkSign.getdktElement());
+                    this.setInsertionLocation(this.sigDKTElement);
+
+                    // Do signature
+                    /**
+                     * Create and append signature
+                     */
+                    dkSign.computeSignature(referenceList, true, this.getInsertionLocation());
+                }
+
+                if (RampartUtil.encryptFirst(rpd)) {
+                    // always add encrypt elements after signature. Because we need to first verify the signature
+                    // and decrypt at receiver end.
+                    this.setInsertionLocation(dkSign.getSignatureElement());
+                } else {
+                    // append timestamp element as next insertion location. Cos in sign and encrypt case the
+                    // receiver first need to decrypt the message => The decryption keys should appear first.
+                    this.setInsertionLocation(this.timestampElement);
+                }
 
-                 ;
-                // Add elements to header
-                 this.sigDKTElement = RampartUtil.insertSiblingAfter(rmd,
-                        this.getInsertionLocation(), dkSign.getdktElement());
-                this.setInsertionLocation(this.sigDKTElement);
-                
-                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd,
-                        this.getInsertionLocation(), dkSign
-                                .getSignatureElement()));
-                                
                 this.mainSigId = RampartUtil
                         .addWsuIdToElement((OMElement) dkSign
                                 .getSignatureElement());
@@ -714,7 +759,7 @@ public class AsymmetricBindingBuilder ex
             }
 
         } else {
-            sig = this.getSignatureBuilder(rmd, sigToken);
+            WSSecSignature sig = this.getSignatureBuilder(rmd, sigToken);
             Element bstElem = sig.getBinarySecurityTokenElement();
             if(bstElem != null) {
                 bstElem = RampartUtil.insertSiblingAfter(rmd, this
@@ -728,18 +773,35 @@ public class AsymmetricBindingBuilder ex
             }
 
             try {
-                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
-                sig.computeSignature();
+                sig.setDigestAlgo(rpd.getAlgorithmSuite().getDigest());
+
+                List<Reference> referenceList
+                        = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+
+                // Do signature
+                if (this.refList == null) {
+                    /**
+                     * If <ReferenceData>..</ReferenceData> is null append <Signature>..</Signature> element
+                     * to current insertion location.
+                     */
+                    sig.computeSignature(referenceList, false, this.getInsertionLocation());
+                } else {
+                    /**
+                     * If <ReferenceData>..</ReferenceData> is not null prepend <Signature>..</Signature> element
+                     * to reference data.
+                     */
+                    sig.computeSignature(referenceList, true, this.refList);
+                }
 
                 signatureElement = sig.getSignatureElement();
-                
-                this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                                rmd, this.getInsertionLocation(), signatureElement));
+
+                this.setInsertionLocation(signatureElement);
 
                 this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) signatureElement);
             } catch (WSSecurityException e) {
                 throw new RampartException("errorInSignatureWithX509Token", e);
             }
+
             signatureValues.add(sig.getSignatureValue());
         }
         
@@ -751,7 +813,7 @@ public class AsymmetricBindingBuilder ex
     }
     
     private void doEncryptionWithSupportingToken(RampartPolicyData rpd, RampartMessageData rmd,
-            Token encrToken, Document doc, Vector encrParts) throws RampartException {
+            Token encrToken, Document doc, List<WSEncryptionPart> encrParts) throws RampartException {
         Element refList = null;
         try {
             if (!(encrToken instanceof X509Token)) {
@@ -813,10 +875,11 @@ public class AsymmetricBindingBuilder ex
                 }
                 
                 //Use the secret from the incoming EncryptedKey element
-                Object resultsObj = rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
+                List<WSHandlerResult> resultsObj
+                        = (List<WSHandlerResult>)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
                 if(resultsObj != null) {
-                    encryptedKeyId = RampartUtil.getRequestEncryptedKeyId((Vector)resultsObj);
-                    encryptedKeyValue = RampartUtil.getRequestEncryptedKeyValue((Vector)resultsObj);
+                    encryptedKeyId = RampartUtil.getRequestEncryptedKeyId(resultsObj);
+                    encryptedKeyValue = RampartUtil.getRequestEncryptedKeyValue(resultsObj);
                     
                     //In the case where we don't have the EncryptedKey in the 
                     //request, for the control to have reached this state,

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/BindingBuilder.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/BindingBuilder.java?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/BindingBuilder.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/BindingBuilder.java Thu Mar  1 09:54:05 2012
@@ -58,14 +58,10 @@ import org.w3c.dom.Element;
 
 import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.xml.crypto.dsig.Reference;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.Vector;
+import java.util.*;
 import java.util.Map.Entry;
 
 public abstract class BindingBuilder {
@@ -75,7 +71,7 @@ public abstract class BindingBuilder {
     
     protected String mainSigId = null;
     
-    protected ArrayList encryptedTokensIdList = new ArrayList();
+    protected ArrayList<String> encryptedTokensIdList = new ArrayList<String>();
     
     protected Element timestampElement;
     
@@ -225,7 +221,8 @@ public abstract class BindingBuilder {
         try {
             RampartUtil.setKeyIdentifierType(rmd, encrKey, token);
             RampartUtil.setEncryptionUser(rmd, encrKey);
-            encrKey.setKeySize(rpd.getAlgorithmSuite().getMaximumSymmetricKeyLength());
+
+            //TODO we do not need to pass keysize as it is taken from algorithm it self - verify
             encrKey.setKeyEncAlgo(rpd.getAlgorithmSuite().getAsymmetricKeyWrap());
             
             encrKey.prepare(doc, RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()));
@@ -354,6 +351,7 @@ public abstract class BindingBuilder {
             throws RampartException {
         
         //Create the list to hold the tokens
+        // TODO putting different types of objects. Need to figure out a way to add single types of objects
         HashMap endSuppTokMap = new HashMap();
         
         if(suppTokens != null && suppTokens.getTokens() != null &&
@@ -361,70 +359,70 @@ public abstract class BindingBuilder {
             log.debug("Processing supporting tokens");
 
             ArrayList tokens = suppTokens.getTokens();
-            for (Iterator iter = tokens.iterator(); iter.hasNext();) {
-                Token token = (Token) iter.next();
+            for (Object objectToken : tokens) {
+                Token token = (Token) objectToken;
                 org.apache.rahas.Token endSuppTok = null;
-                if(token instanceof IssuedToken && rmd.isInitiator()){
-                    String id = RampartUtil.getIssuedToken(rmd, (IssuedToken)token);
+                if (token instanceof IssuedToken && rmd.isInitiator()) {
+                    String id = RampartUtil.getIssuedToken(rmd, (IssuedToken) token);
                     try {
                         endSuppTok = rmd.getTokenStorage().getToken(id);
                     } catch (TrustException e) {
-                        throw new RampartException("errorInRetrievingTokenId", 
+                        throw new RampartException("errorInRetrievingTokenId",
                                 new String[]{id}, e);
                     }
-                    
-                    if(endSuppTok == null) {
-                        throw new RampartException("errorInRetrievingTokenId", 
+
+                    if (endSuppTok == null) {
+                        throw new RampartException("errorInRetrievingTokenId",
                                 new String[]{id});
                     }
-                    
+
                     //Add the token to the header
                     Element siblingElem = RampartUtil
                             .insertSiblingAfter(rmd, this.getInsertionLocation(),
                                     (Element) endSuppTok.getToken());
                     this.setInsertionLocation(siblingElem);
-                    
+
                     if (suppTokens.isEncryptedToken()) {
                         this.encryptedTokensIdList.add(endSuppTok.getId());
                     }
-                    
+
                     //Add the extracted token
                     endSuppTokMap.put(token, endSuppTok);
-                    
-                } else if(token instanceof X509Token) {
 
-                        //We have to use a cert
-                        //Prepare X509 signature
-                        WSSecSignature sig = this.getSignatureBuilder(rmd, token);
-                        Element bstElem = sig.getBinarySecurityTokenElement();
-                        if(bstElem != null) {   
-                            bstElem = RampartUtil.insertSiblingAfter(rmd, 
-                                    this.getInsertionLocation(), bstElem);
-                            this.setInsertionLocation(bstElem);
-                            
-                            SupportingPolicyData supportingPolcy = new SupportingPolicyData();
-                            supportingPolcy.build(suppTokens);
-                            supportingPolcy.setSignatureToken(token);
-                            supportingPolcy.setEncryptionToken(token);
-                            rmd.getPolicyData().addSupportingPolicyData(supportingPolcy);
-                            
-                            if (suppTokens.isEncryptedToken()) {
-                                this.encryptedTokensIdList.add(sig.getBSTTokenId());
-                            }
+                } else if (token instanceof X509Token) {
+
+                    //We have to use a cert
+                    //Prepare X509 signature
+                    WSSecSignature sig = this.getSignatureBuilder(rmd, token);
+                    Element bstElem = sig.getBinarySecurityTokenElement();
+                    if (bstElem != null) {
+                        bstElem = RampartUtil.insertSiblingAfter(rmd,
+                                this.getInsertionLocation(), bstElem);
+                        this.setInsertionLocation(bstElem);
+
+                        SupportingPolicyData supportingPolcy = new SupportingPolicyData();
+                        supportingPolcy.build(suppTokens);
+                        supportingPolcy.setSignatureToken(token);
+                        supportingPolcy.setEncryptionToken(token);
+                        rmd.getPolicyData().addSupportingPolicyData(supportingPolcy);
+
+                        if (suppTokens.isEncryptedToken()) {
+                            this.encryptedTokensIdList.add(sig.getBSTTokenId());
                         }
-                        endSuppTokMap.put(token, sig);
-                        
-                } else if(token instanceof UsernameToken) {
-                    WSSecUsernameToken utBuilder = addUsernameToken(rmd, (UsernameToken)token);
-                    
+                    }
+                    endSuppTokMap.put(token, sig);
+
+                } else if (token instanceof UsernameToken) {
+                    WSSecUsernameToken utBuilder = addUsernameToken(rmd, (UsernameToken) token);
+
                     utBuilder.prepare(rmd.getDocument());
-                    
+
                     //Add the UT
                     Element elem = utBuilder.getUsernameTokenElement();
                     elem = RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(), elem);
-                    
+
                     encryptedTokensIdList.add(utBuilder.getId());
-                    
+
                     //Move the insert location to the next element
                     this.setInsertionLocation(elem);
                     Date now = new Date();
@@ -447,27 +445,28 @@ public abstract class BindingBuilder {
      * @param sigParts
      * @throws RampartException
      */
-    protected Vector addSignatureParts(HashMap tokenMap, Vector sigParts) throws RampartException {
+    protected List<WSEncryptionPart> addSignatureParts(HashMap tokenMap, List<WSEncryptionPart> sigParts)
+            throws RampartException {
     	
         Set entrySet = tokenMap.entrySet();
-        
-        for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
-            Object tempTok =  ((Entry)iter.next()).getValue();
+
+        for (Object anEntrySet : entrySet) {
+            Object tempTok = ((Entry) anEntrySet).getValue();
             WSEncryptionPart part = null;
-            
-            if(tempTok instanceof org.apache.rahas.Token) {
-            	
+
+            if (tempTok instanceof org.apache.rahas.Token) {
+
                 part = new WSEncryptionPart(
                         ((org.apache.rahas.Token) tempTok).getId());
-                
-            } else if(tempTok instanceof WSSecSignature) {
+
+            } else if (tempTok instanceof WSSecSignature) {
                 WSSecSignature tempSig = (WSSecSignature) tempTok;
-                if(tempSig.getBSTTokenId() != null) {
+                if (tempSig.getBSTTokenId() != null) {
                     part = new WSEncryptionPart(tempSig.getBSTTokenId());
                 }
             } else {
-            	
-              throw new RampartException("UnsupportedTokenInSupportingToken");  
+
+                throw new RampartException("UnsupportedTokenInSupportingToken");
             }
             sigParts.add(part);
         }
@@ -485,45 +484,55 @@ public abstract class BindingBuilder {
     }
     
     
-    protected Vector doEndorsedSignatures(RampartMessageData rmd, HashMap tokenMap) throws RampartException {
+    protected List<byte[]> doEndorsedSignatures(RampartMessageData rmd, HashMap tokenMap) throws RampartException {
         
         Set tokenSet = tokenMap.keySet();
         
-        Vector sigValues = new Vector();
-        
-        for (Iterator iter = tokenSet.iterator(); iter.hasNext();) {
-            
-            Token token = (Token)iter.next();
-            
+        List<byte[]> sigValues = new ArrayList<byte[]>();
+
+        for (Object aTokenSet : tokenSet) {
+
+            Token token = (Token) aTokenSet;
+
             Object tempTok = tokenMap.get(token);
-            
-            Vector sigParts = new Vector();
+
+            // Migrating to a list
+            List<WSEncryptionPart> sigParts = new ArrayList<WSEncryptionPart>();
             sigParts.add(new WSEncryptionPart(this.mainSigId));
-            
+
             if (tempTok instanceof org.apache.rahas.Token) {
-                org.apache.rahas.Token tok = (org.apache.rahas.Token)tempTok;
-                if(rmd.getPolicyData().isTokenProtection()) {
+                org.apache.rahas.Token tok = (org.apache.rahas.Token) tempTok;
+                if (rmd.getPolicyData().isTokenProtection()) {
                     sigParts.add(new WSEncryptionPart(tok.getId()));
                 }
-                
-                this.doSymmSignature(rmd, token, (org.apache.rahas.Token)tempTok, sigParts);
-                
+
+                this.doSymmSignature(rmd, token, (org.apache.rahas.Token) tempTok, sigParts);
+
             } else if (tempTok instanceof WSSecSignature) {
-                WSSecSignature sig = (WSSecSignature)tempTok;
-                if(rmd.getPolicyData().isTokenProtection() &&
+                WSSecSignature sig = (WSSecSignature) tempTok;
+                if (rmd.getPolicyData().isTokenProtection() &&
                         sig.getBSTTokenId() != null) {
                     sigParts.add(new WSEncryptionPart(sig.getBSTTokenId()));
                 }
-                
+
                 try {
-                    sig.addReferencesToSign(sigParts, rmd.getSecHeader());
-                    sig.computeSignature();
-                    
-                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                            rmd, 
-                            this.getInsertionLocation(), 
-                            sig.getSignatureElement()));
-                    
+
+
+                    List<Reference> referenceList
+                            = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+
+                    /**
+                     * Before migration it was - this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this
+                     *       .getInsertionLocation(), supportingSignatureElement));
+                     *
+                     * In this case we need to append <Signature>..</Signature> element to
+                     * current insertion location
+                     */
+
+                    sig.computeSignature(referenceList, false, this.getInsertionLocation());
+
+                    this.setInsertionLocation(sig.getSignatureElement());
+
                 } catch (WSSecurityException e) {
                     throw new RampartException("errorInSignatureWithX509Token", e);
                 }
@@ -536,7 +545,8 @@ public abstract class BindingBuilder {
     }
     
     
-    protected byte[] doSymmSignature(RampartMessageData rmd, Token policyToken, org.apache.rahas.Token tok, Vector sigParts) throws RampartException {
+    protected byte[] doSymmSignature(RampartMessageData rmd, Token policyToken, org.apache.rahas.Token tok,
+                                     List<WSEncryptionPart> sigParts) throws RampartException {
         
         Document doc = rmd.getDocument();
         
@@ -563,7 +573,7 @@ public abstract class BindingBuilder {
                 
                 // Setting the AttachedReference or the UnattachedReference according to the flag
                 OMElement ref;
-                if (attached == true) {
+                if (attached) {
                     ref = tok.getAttachedReference();
                 } else {
                     ref = tok.getUnattachedReference();
@@ -582,6 +592,7 @@ public abstract class BindingBuilder {
                 	    tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken)tok).getSHA1());;
                 	}
                 	dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());
+                    tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);  // TODO check this
                 
                 } else {
                     dkSign.setExternalKey(tok.getSecret(), tok.getId());
@@ -611,36 +622,45 @@ public abstract class BindingBuilder {
                 
                 dkSign.setParts(sigParts);
                 
-                dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
-                
-                //Do signature
-                dkSign.computeSignature();
+                List<Reference> referenceList
+                        = dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
 
                 //Add elements to header
-                
+                //Do signature
                 if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
-                        this.getInsertionLocation() == null ) {
-                    this.setInsertionLocation(RampartUtil
-                            
-                            .insertSiblingBefore(rmd, 
-                                    this.mainRefListElement,
-                                    dkSign.getdktElement()));
-
-                        this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                                rmd, 
-                                this.getInsertionLocation(), 
-                                dkSign.getSignatureElement()));                
+                        this.mainRefListElement != null ) {
+
+                     /**
+                     * <xenc:ReferenceList>
+                     *     <xenc:DataReference URI="#EncDataId-2"/>
+                     * </xenc:ReferenceList>
+                     * If there is a reference list as above we need to first prepend reference list
+                     * with the new derived key. Then we need to prepend Signature to newly added derived key.
+                     */
+
+                    // Add DeriveKey before ReferenceList
+                    RampartUtil.insertSiblingBefore(rmd, this.mainRefListElement, dkSign.getdktElement());
+
+                    // Insert signature before DerivedKey
+                    dkSign.computeSignature(referenceList, true, dkSign.getdktElement());
+                    this.setInsertionLocation(this.mainRefListElement);
                 } else {
-                    this.setInsertionLocation(RampartUtil
-                
-                        .insertSiblingAfter(rmd, 
-                                this.getInsertionLocation(),
-                                dkSign.getdktElement()));
-
-                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                            rmd, 
-                            this.getInsertionLocation(), 
-                            dkSign.getSignatureElement()));
+
+                    /**
+                     * Add <wsc:DerivedKeyToken>..</wsc:DerivedKeyToken> to security
+                     * header.
+                     */
+                    dkSign.appendDKElementToHeader(rmd.getSecHeader());
+
+                    this.setInsertionLocation(dkSign.getdktElement());
+
+                    /**
+                     * In this case we need to insert <Signature>..</Signature> element
+                     * before this.mainRefListElement element. In other words we need to
+                     * prepend <Signature>...</Signature> element to this.mainRefListElement.
+                     */
+                    dkSign.computeSignature(referenceList, false, this.getInsertionLocation());
+                    this.setInsertionLocation(dkSign.getSignatureElement());
                 }
 
                 return dkSign.getSignatureValue();
@@ -671,8 +691,8 @@ public abstract class BindingBuilder {
                     }
 
                 } else if (policyToken instanceof IssuedToken) {
-                    sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS
-                            + WSConstants.SAML_ASSERTION_ID);
+
+                    sig.setCustomTokenValueType(RampartUtil.getSAML10AssertionNamespace());
                     sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                 }
                 
@@ -702,31 +722,42 @@ public abstract class BindingBuilder {
                 
                 sig.setCustomTokenId(sigTokId);
                 sig.setSecretKey(tok.getSecret());
-                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
+                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());// TODO one is redundant ?..
                 sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                 sig.prepare(rmd.getDocument(), RampartUtil.getSignatureCrypto(rpd
                         .getRampartConfig(), rmd.getCustomClassLoader()),
                         rmd.getSecHeader());
 
                 sig.setParts(sigParts);
-                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+                List<Reference> referenceList
+                        = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
 
                 //Do signature
-                sig.computeSignature();
+                if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING)
+                        && this.mainRefListElement != null) {
 
-                if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING) &&
-                        this.getInsertionLocation() == null) {
-                    this.setInsertionLocation(RampartUtil.insertSiblingBefore(
-                            rmd,
-                            this.mainRefListElement,
-                            sig.getSignatureElement()));                    
+                    /**
+                     * In this case we need to insert <Signature>..</Signature> element
+                     * before this.mainRefListElement element. In other words we need to
+                     * prepend <Signature>...</Signature> element to this.mainRefListElement.
+                     * this.mainRefListElement is equivalent to
+                     * <xenc:ReferenceList>
+                     *     <xenc:DataReference URI="#EncDataId-2"/>
+                     * </xenc:ReferenceList>
+                     */
+                    sig.computeSignature(referenceList, true, this.mainRefListElement);
+                    this.setInsertionLocation(this.mainRefListElement);
                 } else {
-                    this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                            rmd,
-                            this.getInsertionLocation(),
-                            sig.getSignatureElement()));     
+
+                    /**
+                     * In this case we need to append <Signature>..</Signature> element to
+                     * current insertion location.
+                     */
+                    sig.computeSignature(referenceList, false, this.getInsertionLocation());
+                    this.setInsertionLocation(sig.getSignatureElement());
                 }
 
+
                 return sig.getSignatureValue();
                 
             } catch (WSSecurityException e) {
@@ -746,7 +777,7 @@ public abstract class BindingBuilder {
      */
     protected org.apache.rahas.Token getToken(RampartMessageData rmd, 
                     String tokenId) throws RampartException {
-        org.apache.rahas.Token tok = null;
+        org.apache.rahas.Token tok;
         try {
             tok = rmd.getTokenStorage().getToken(tokenId);
         } catch (TrustException e) {
@@ -762,7 +793,7 @@ public abstract class BindingBuilder {
     }
     
 
-    protected void addSignatureConfirmation(RampartMessageData rmd, Vector sigParts) {
+    protected void addSignatureConfirmation(RampartMessageData rmd, List<WSEncryptionPart> sigParts) {
         
         if(!rmd.getPolicyData().isSignatureConfirmation()) {
             
@@ -771,16 +802,17 @@ public abstract class BindingBuilder {
         }
         
         Document doc = rmd.getDocument();
-        
-        Vector results = (Vector)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
+
+        List<WSHandlerResult> results
+                = (List<WSHandlerResult>)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
         /*
          * loop over all results gathered by all handlers in the chain. For each
          * handler result get the various actions. After that loop we have all
-         * signature results in the signatureActions vector
+         * signature results in the signatureActions list.
          */
-        Vector signatureActions = new Vector();
-        for (int i = 0; i < results.size(); i++) {
-            WSHandlerResult wshResult = (WSHandlerResult) results.get(i);
+        List<WSSecurityEngineResult> signatureActions = new ArrayList<WSSecurityEngineResult>();
+        for (Object result : results) {
+            WSHandlerResult wshResult = (WSHandlerResult) result;
 
             WSSecurityUtil.fetchAllActionResults(wshResult.getResults(),
                     WSConstants.SIGN, signatureActions);
@@ -797,14 +829,12 @@ public abstract class BindingBuilder {
                 log.debug("Signature Confirmation: number of Signature results: "
                         + signatureActions.size());
             }
-            for (int i = 0; i < signatureActions.size(); i++) {
-                WSSecurityEngineResult wsr = (WSSecurityEngineResult) signatureActions
-                        .get(i);
-                byte[] sigVal = (byte[]) wsr.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE);
+            for (WSSecurityEngineResult signatureAction : signatureActions) {
+                byte[] sigVal = (byte[]) signatureAction.get(WSSecurityEngineResult.TAG_SIGNATURE_VALUE);
                 wsc.setSignatureValue(sigVal);
                 wsc.prepare(doc);
                 RampartUtil.appendChildToSecHeader(rmd, wsc.getSignatureConfirmationElement());
-                if(sigParts != null) {
+                if (sigParts != null) {
                     sigParts.add(new WSEncryptionPart(wsc.getId()));
                 }
             }

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/SymmetricBindingBuilder.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/SymmetricBindingBuilder.java?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/SymmetricBindingBuilder.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/SymmetricBindingBuilder.java Thu Mar  1 09:54:05 2012
@@ -53,10 +53,7 @@ import org.w3c.dom.Element;
 
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Vector;
+import java.util.*;
 
 
 public class SymmetricBindingBuilder extends BindingBuilder {
@@ -95,16 +92,16 @@ public class SymmetricBindingBuilder ext
     	       	
         RampartPolicyData rpd = rmd.getPolicyData();
         
-        Vector signatureValues = new Vector();
+        List<byte[]> signatureValues = new ArrayList<byte[]>();
         
     	if(tlog.isDebugEnabled()){
     		t0 = System.currentTimeMillis();
     	}
         
         Token encryptionToken = rpd.getEncryptionToken();
-        Vector encrParts = RampartUtil.getEncryptedParts(rmd);
+        List<WSEncryptionPart> encrParts = RampartUtil.getEncryptedParts(rmd);
 
-        Vector sigParts = RampartUtil.getSignedParts(rmd);
+        List<WSEncryptionPart> sigParts = RampartUtil.getSignedParts(rmd);
         
         if(encryptionToken == null && encrParts.size() > 0) {
             throw new RampartException("encryptionTokenMissing");
@@ -217,7 +214,8 @@ public class SymmetricBindingBuilder ext
                 // SymmKey is already encrypted, no need to do it again
                 encr.setEncryptSymmKey(false);
                 if (!rmd.isInitiator() && tok instanceof EncryptedKeyToken) {
-                    encr.setUseKeyIdentifier(true);
+                    // TODO was encr.setUseKeyIdentifier(true); - verify
+                    encr.setEncKeyIdDirectId(true);
                     encr.setCustomReferenceValue(((EncryptedKeyToken)tok).getSHA1());
                     encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                 }
@@ -282,9 +280,9 @@ public class SymmetricBindingBuilder ext
                 SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();           
                 sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
                 
-                Vector supportingToks = rpd.getSupportingTokensList();
-                for (int i = 0; i < supportingToks.size(); i++) {
-                    this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
+                List<SupportingToken> supportingToks = rpd.getSupportingTokensList();
+                for (SupportingToken supportingTok : supportingToks) {
+                    this.handleSupportingTokens(rmd, supportingTok);
                 } 
                 
                 SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
@@ -312,16 +310,16 @@ public class SymmetricBindingBuilder ext
                 
                 endSuppTokMap.putAll(endEncSuppTokMap);
                 //Do endorsed signatures
-                Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
-                for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
-                    signatureValues.add(iter.next());
+                List<byte[]> endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
+                for (byte[] endSigVal : endSigVals) {
+                    signatureValues.add(endSigVal);
                 }
                 
                 sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
                 //Do signed endorsing signatures
-                Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
-                for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
-                    signatureValues.add(iter.next());
+                List<byte[]> sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
+                for (byte[] sigEndSigVal : sigEndSigVals) {
+                    signatureValues.add(sigEndSigVal);
                 }
             }
             
@@ -339,7 +337,7 @@ public class SymmetricBindingBuilder ext
             		t3 = System.currentTimeMillis();
             	}
                 log.debug("Signature protection");
-                Vector secondEncrParts = new Vector();
+                List<WSEncryptionPart> secondEncrParts = new ArrayList<WSEncryptionPart>();
                 
                 //Now encrypt the signature using the above token
                 if(rpd.isSignatureProtection()) {
@@ -347,8 +345,8 @@ public class SymmetricBindingBuilder ext
                 }
                 
                 if(rmd.isInitiator()) {
-                    for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
-                        secondEncrParts.add(new WSEncryptionPart((String)encryptedTokensIdList.get(i),"Element"));
+                    for (String anEncryptedTokensIdList : encryptedTokensIdList) {
+                        secondEncrParts.add(new WSEncryptionPart(anEncryptedTokensIdList, "Element"));
                     }
                 }
                 
@@ -410,7 +408,7 @@ public class SymmetricBindingBuilder ext
         
         Element sigTokElem = null;
         
-        Vector signatureValues = new Vector();
+        List<byte[]> signatureValues = new ArrayList<byte[]>();
         
         if(sigToken != null) {
             if(sigToken instanceof SecureConversationToken) {
@@ -457,7 +455,7 @@ public class SymmetricBindingBuilder ext
         HashMap endEncSuppTokMap = null;
         HashMap sgndEndEncSuppTokMap = null;
         
-        Vector sigParts = RampartUtil.getSignedParts(rmd);
+        List<WSEncryptionPart> sigParts = RampartUtil.getSignedParts(rmd);
         
         if(this.timestampElement != null){
         	sigParts.add(new WSEncryptionPart(RampartUtil
@@ -484,9 +482,9 @@ public class SymmetricBindingBuilder ext
             SupportingToken sgndEndEncSuppTokens = rpd.getSignedEndorsingEncryptedSupportingTokens();           
             sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);
             
-            Vector supportingToks = rpd.getSupportingTokensList();
-            for (int i = 0; i < supportingToks.size(); i++) {
-                this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
+            List<SupportingToken> supportingToks = rpd.getSupportingTokensList();
+            for (SupportingToken supportingTok : supportingToks) {
+                this.handleSupportingTokens(rmd, supportingTok);
             } 
             
             SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
@@ -514,18 +512,18 @@ public class SymmetricBindingBuilder ext
             // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
             endSuppTokMap.putAll(endEncSuppTokMap);
             //Do endorsed signatures
-            Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
-            
-            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
-                signatureValues.add(iter.next());
+            List<byte[]> endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
+
+            for (byte[] endSigVal : endSigVals) {
+                signatureValues.add(endSigVal);
             }
              
             //Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
             sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
             //Do signed endorsing signatures
-            Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
-            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
-                signatureValues.add(iter.next());
+            List<byte[]> sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
+            for (byte[] sigEndSigVal : sigEndSigVals) {
+                signatureValues.add(sigEndSigVal);
             }
         }
         
@@ -556,7 +554,7 @@ public class SymmetricBindingBuilder ext
             
         }
     
-        Vector encrParts = RampartUtil.getEncryptedParts(rmd);
+        List<WSEncryptionPart> encrParts = RampartUtil.getEncryptedParts(rmd);
         
         //Check for signature protection
         if(rpd.isSignatureProtection() && this.mainSigId != null) {
@@ -565,8 +563,8 @@ public class SymmetricBindingBuilder ext
         }
         
         if(rmd.isInitiator()) {
-            for (int i = 0 ; i < encryptedTokensIdList.size(); i++) {
-                encrParts.add(new WSEncryptionPart((String)encryptedTokensIdList.get(i),"Element"));
+            for (String anEncryptedTokensIdList : encryptedTokensIdList) {
+                encrParts.add(new WSEncryptionPart(anEncryptedTokensIdList, "Element"));
             }
         }
         
@@ -581,8 +579,8 @@ public class SymmetricBindingBuilder ext
                     //Check whether it is security policy 1.2 and use the secure conversation accordingly
                     if (SPConstants.SP_V12 == encrToken.getVersion()) {
                         dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
-                    }                    
-                    
+                    }
+
                     if(encrTokElem != null && encrTok.getAttachedReference() != null) {
                         
                         dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc
@@ -602,6 +600,7 @@ public class SymmetricBindingBuilder ext
                     	    tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken)encrTok).getSHA1());
                     	}
                     	dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());
+                        tokenRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);  // TODO check this
                     	
                     } else {
                         dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
@@ -657,7 +656,8 @@ public class SymmetricBindingBuilder ext
                     // Use key identifier in the KeyInfo in server side
                     if (!rmd.isInitiator()) {
                         if(encrTok instanceof EncryptedKeyToken) {
-                            encr.setUseKeyIdentifier(true);
+                            // TODO was encr.setUseKeyIdentifier(true); verify
+                            encr.setEncKeyIdDirectId(true);
                             encr.setCustomReferenceValue(((EncryptedKeyToken)encrTok).getSHA1());
                             encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                         } 
@@ -757,49 +757,47 @@ public class SymmetricBindingBuilder ext
         
         return Base64.encode(data);
     }
-    
-    private String getEncryptedKey(RampartMessageData rmd ) throws RampartException {
-    	
-    	Vector results = (Vector)rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
-    	
-        for (int i = 0; i < results.size(); i++) {
-            WSHandlerResult rResult =
-                    (WSHandlerResult) results.get(i);
-
-            Vector wsSecEngineResults = rResult.getResults();
-            
-            for (int j = 0; j < wsSecEngineResults.size(); j++) {
-                WSSecurityEngineResult wser =
-                        (WSSecurityEngineResult) wsSecEngineResults.get(j);
-                Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
-                if (actInt.intValue() == WSConstants.ENCR) {
-                    
-                	if (wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID) != null &&
-                	        ((String)wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID)).length() != 0) {
-                		
-                		try {
-                			
-	                		String encryptedKeyID = (String)wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID);
-	                		
-	                        Date created = new Date();
-	                        Date expires = new Date();
-	                        expires.setTime(System.currentTimeMillis() + 300000);
-	                        EncryptedKeyToken tempTok = new EncryptedKeyToken(encryptedKeyID,created,expires);
-	                        tempTok.setSecret((byte[])wser.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY));
-	                        tempTok.setSHA1(getSHA1((byte[])wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
-	                        rmd.getTokenStorage().add(tempTok);
-	                        
-	                        return encryptedKeyID;
-                        
-                		} catch (TrustException e) {
-                			throw new RampartException("errorInAddingTokenIntoStore");
-                		}
-                		
-                	}
+
+    private String getEncryptedKey(RampartMessageData rmd) throws RampartException {
+
+        List<WSHandlerResult> results
+                = (List<WSHandlerResult>) rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);
+
+        for (WSHandlerResult result : results) {
+
+            List<WSSecurityEngineResult> wsSecEngineResults = result.getResults();
+
+            for (WSSecurityEngineResult wsSecEngineResult : wsSecEngineResults) {
+                Integer actInt = (Integer) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ACTION);
+                if (actInt == WSConstants.ENCR) {
+
+                    if (wsSecEngineResult.get(WSSecurityEngineResult.TAG_ID) != null &&
+                            ((String) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ID)).length() != 0) {
+
+                        try {
+
+                            String encryptedKeyID = (String) wsSecEngineResult.get(WSSecurityEngineResult.TAG_ID);
+
+                            Date created = new Date();
+                            Date expires = new Date();
+                            expires.setTime(System.currentTimeMillis() + 300000);
+                            EncryptedKeyToken tempTok = new EncryptedKeyToken(encryptedKeyID, created, expires);
+                            tempTok.setSecret((byte[]) wsSecEngineResult.get(WSSecurityEngineResult.TAG_SECRET));
+                            tempTok.setSHA1(getSHA1((byte[]) wsSecEngineResult.
+                                    get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
+                            rmd.getTokenStorage().add(tempTok);
+
+                            return encryptedKeyID;
+
+                        } catch (TrustException e) {
+                            throw new RampartException("errorInAddingTokenIntoStore");
+                        }
+
+                    }
                 }
             }
         }
-    	return null;
+        return null;
     }
     
     

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/TransportBindingBuilder.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/TransportBindingBuilder.java?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/TransportBindingBuilder.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/builder/TransportBindingBuilder.java Thu Mar  1 09:54:05 2012
@@ -43,16 +43,14 @@ import org.apache.ws.security.WSEncrypti
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.conversation.ConversationException;
 import org.apache.ws.security.handler.WSHandlerConstants;
-import org.apache.ws.security.message.WSSecDKSign;
-import org.apache.ws.security.message.WSSecEncryptedKey;
-import org.apache.ws.security.message.WSSecSignature;
-import org.apache.ws.security.message.WSSecUsernameToken;
+import org.apache.ws.security.message.*;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
+import javax.xml.crypto.dsig.Reference;
 import java.util.ArrayList;
 import java.util.Iterator;
-import java.util.Vector;
+import java.util.List;
 
 public class TransportBindingBuilder extends BindingBuilder {
 
@@ -78,7 +76,7 @@ public class TransportBindingBuilder ext
          * Process Supporting tokens
          */
         if(rmd.isInitiator()) {
-            Vector signatureValues = new Vector();
+            List<byte[]> signatureValues = new ArrayList<byte[]>();
             
             SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
             
@@ -88,21 +86,21 @@ public class TransportBindingBuilder ext
                 log.debug("Processing signed supporting tokens");
 
                 ArrayList tokens = sgndSuppTokens.getTokens();
-                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
-                    
-                    Token token = (Token) iter.next();
-                    if(token instanceof UsernameToken) {
-                        WSSecUsernameToken utBuilder = addUsernameToken(rmd,(UsernameToken)token);
-                        
+                for (Object signedSupportingToken : tokens) {
+
+                    Token token = (Token) signedSupportingToken;
+                    if (token instanceof UsernameToken) {
+                        WSSecUsernameToken utBuilder = addUsernameToken(rmd, (UsernameToken) token);
+
                         utBuilder.prepare(rmd.getDocument());
-                        
+
                         //Add the UT
                         utBuilder.appendToHeader(rmd.getSecHeader());
-                        
+
                     } else {
-                        throw new RampartException("unsupportedSignedSupportingToken", 
-                                new String[]{"{" +token.getName().getNamespaceURI() 
-                                + "}" + token.getName().getLocalPart()});
+                        throw new RampartException("unsupportedSignedSupportingToken",
+                                new String[]{"{" + token.getName().getNamespaceURI()
+                                        + "}" + token.getName().getLocalPart()});
                     }
                 }
             }
@@ -115,11 +113,11 @@ public class TransportBindingBuilder ext
 
                 ArrayList tokens = sgndEndSuppTokens.getTokens();
                 SignedEncryptedParts signdParts = sgndEndSuppTokens.getSignedParts();
-                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
-                    Token token = (Token) iter.next();
-                    if(token instanceof IssuedToken && rmd.isInitiator()) {
+                for (Object objectToken : tokens) {
+                    Token token = (Token) objectToken;
+                    if (token instanceof IssuedToken && rmd.isInitiator()) {
                         signatureValues.add(doIssuedTokenSignature(rmd, token, signdParts));
-                    } else if(token instanceof X509Token) {
+                    } else if (token instanceof X509Token) {
                         signatureValues.add(doX509TokenSignature(rmd, token, signdParts));
                     }
                 }
@@ -131,27 +129,27 @@ public class TransportBindingBuilder ext
                 log.debug("Processing endorsing supporting tokens");
                 ArrayList tokens = endSupptokens.getTokens();
                 SignedEncryptedParts signdParts = endSupptokens.getSignedParts();
-                for (Iterator iter = tokens.iterator(); iter.hasNext();) {
-                    Token token = (Token) iter.next();
-                    if(token instanceof IssuedToken && rmd.isInitiator()){
+                for (Object objectToken : tokens) {
+                    Token token = (Token) objectToken;
+                    if (token instanceof IssuedToken && rmd.isInitiator()) {
                         signatureValues.add(doIssuedTokenSignature(rmd, token, signdParts));
-                    } else if(token instanceof X509Token) {
+                    } else if (token instanceof X509Token) {
                         signatureValues.add(doX509TokenSignature(rmd, token, signdParts));
                     } else if (token instanceof SecureConversationToken) {
-                        handleSecureConversationTokens(rmd, (SecureConversationToken)token);
-                        signatureValues.add(doSecureConversationSignature(rmd, token, signdParts));                                               
+                        handleSecureConversationTokens(rmd, (SecureConversationToken) token);
+                        signatureValues.add(doSecureConversationSignature(rmd, token, signdParts));
                     }
                 }
             }
             
             
-            Vector supportingToks = rpd.getSupportingTokensList();
-            for (int i = 0; i < supportingToks.size(); i++) {
-                this.handleSupportingTokens(rmd, (SupportingToken)supportingToks.get(i));
+            List<SupportingToken> supportingToks = rpd.getSupportingTokensList();
+            for (SupportingToken supportingTok : supportingToks) {
+                this.handleSupportingTokens(rmd, supportingTok);
             } 
             
             
-            //Store the signature values vector
+            //Store the signature values list
             rmd.getMsgContext().setProperty(WSHandlerConstants.SEND_SIGV, signatureValues);
         } else {
             addSignatureConfirmation(rmd, null);
@@ -176,7 +174,7 @@ public class TransportBindingBuilder ext
         RampartPolicyData rpd = rmd.getPolicyData();
         Document doc = rmd.getDocument();
         
-        Vector sigParts = new Vector();
+        List<WSEncryptionPart> sigParts = new ArrayList<WSEncryptionPart>();
         
         if(this.timestampElement != null){
             sigParts.add(new WSEncryptionPart(rmd.getTimestampId()));                          
@@ -209,7 +207,9 @@ public class TransportBindingBuilder ext
                 if(bstElem != null) {
                    RampartUtil.appendChildToSecHeader(rmd, bstElem); 
                 }
-                
+
+                // Add <xenc:EncryptedKey Id="EncKeyId-E67B75302ACB3BEDF313277587471272">..</xenc:EncryptedKey>
+                // to security header.
                 encrKey.appendToHeader(rmd.getSecHeader());
                 
                 WSSecDKSign dkSig = new WSSecDKSign();
@@ -219,7 +219,10 @@ public class TransportBindingBuilder ext
                 dkSig.setSigCanonicalization(rpd.getAlgorithmSuite().getInclusiveC14n());
                 dkSig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
                 dkSig.setDerivedKeyLength(rpd.getAlgorithmSuite().getSignatureDerivedKeyLength()/8);
-                
+
+                /**
+                 * Add a reference to encrypted key in the derived key
+                 */
                 dkSig.setExternalKey(encrKey.getEphemeralKey(), encrKey.getId());
                 
                 dkSig.prepare(doc, rmd.getSecHeader());
@@ -231,15 +234,26 @@ public class TransportBindingBuilder ext
                 
                 dkSig.setParts(sigParts);
                 
-                dkSig.addReferencesToSign(sigParts, rmd.getSecHeader());
-                
-                //Do signature
-                dkSig.computeSignature();
-                
+                List<Reference> referenceList
+                        = dkSig.addReferencesToSign(sigParts, rmd.getSecHeader());
+
+
+                /**
+                 * Add <wsc:DerivedKeyToken>..</wsc:DerivedKeyToken> to security
+                 * header. We need to add this just after Encrypted Key and just before <Signature>..</Signature>
+                 * elements. (As a convention)
+                 */
                 dkSig.appendDKElementToHeader(rmd.getSecHeader());
 
-                dkSig.appendSigToHeader(rmd.getSecHeader());
+                //Do signature and append to the security header
+                dkSig.computeSignature(referenceList, false, null);
                 
+
+
+                // TODO this is bit dubious, before migration code was like "dkSig.appendSigToHeader(rmd.getSecHeader())"
+                // but WSS4J has remove append methods. Need to find why ?
+                //this.appendToHeader(rmd.getSecHeader(), dkSig.getSignatureElement());
+
                 return dkSig.getSignatureValue();
                 
             } catch (WSSecurityException e) {
@@ -261,13 +275,14 @@ public class TransportBindingBuilder ext
                     sigParts.add(new WSEncryptionPart(sig.getBSTTokenId()));
                 }
                 
-                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
-                
-                sig.appendToHeader(rmd.getSecHeader());
-                
-                sig.computeSignature();
-                
-                return sig.getSignatureValue();    
+                List<Reference> referenceList
+                        = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+
+                // TODO changed the order - verify
+                // Compute signature and append to the header
+                sig.computeSignature(referenceList, false, null);
+
+                return sig.getSignatureValue();
             } catch (WSSecurityException e) {
                 throw new RampartException("errorInSignatureWithX509Token", e);
             }
@@ -277,6 +292,15 @@ public class TransportBindingBuilder ext
         
     }
 
+    private void appendToHeader(WSSecHeader secHeader, Element appendingChild) {
+
+        // TODO this is bit dubious, before migration code was like "dkSig.appendSigToHeader(rmd.getSecHeader())"
+        // but WSS4J has remove append methods. Need to find why ?
+        Element secHeaderElement = secHeader.getSecurityHeader();
+        secHeaderElement.appendChild(appendingChild);
+
+    }
+
 
     /**
      * IssuedToken signature
@@ -316,7 +340,7 @@ public class TransportBindingBuilder ext
             tokenIncluded = true;
         }
 
-        Vector sigParts = new Vector();
+        List<WSEncryptionPart> sigParts = new ArrayList<WSEncryptionPart>();
         
         if(this.timestampElement != null){
             sigParts.add(new WSEncryptionPart(rmd.getTimestampId()));                          
@@ -334,9 +358,9 @@ public class TransportBindingBuilder ext
             }
     
             ArrayList headers = signdParts.getHeaders();
-            for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
-                Header header = (Header) iterator.next();
-                WSEncryptionPart wep = new WSEncryptionPart(header.getName(), 
+            for (Object signedHeader : headers) {
+                Header header = (Header) signedHeader;
+                WSEncryptionPart wep = new WSEncryptionPart(header.getName(),
                         header.getNamespace(),
                         "Content");
                 sigParts.add(wep);
@@ -354,7 +378,7 @@ public class TransportBindingBuilder ext
               
               // Setting the AttachedReference or the UnattachedReference according to the flag
               OMElement ref;
-              if (tokenIncluded == true) {
+              if (tokenIncluded) {
                   ref = tok.getAttachedReference();
               } else {
                   ref = tok.getUnattachedReference();
@@ -372,17 +396,24 @@ public class TransportBindingBuilder ext
               dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength());
               
               dkSign.prepare(doc);
-              
+
+              /**
+               * Add <wsc:DerivedKeyToken>..</wsc:DerivedKeyToken> to security
+               * header. We need to add this just after Encrypted Key and just before <Signature>..</Signature>
+               * elements. (As a convention)
+               */
               dkSign.appendDKElementToHeader(rmd.getSecHeader());
               
               dkSign.setParts(sigParts);
               
-              dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
+              List<Reference> referenceList
+                      = dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
               
               //Do signature
-              dkSign.computeSignature();
-              
-              dkSign.appendSigToHeader(rmd.getSecHeader());
+              dkSign.computeSignature(referenceList, false, null);
+
+              // TODO verify before migration - dkSign.appendSigToHeader(rmd.getSecHeader())
+              // this.appendToHeader(rmd.getSecHeader(), dkSign.getSignatureElement());
               
               return dkSign.getSignatureValue();
               
@@ -403,8 +434,7 @@ public class TransportBindingBuilder ext
 		    tokId = tokId.substring(1);
                 }
                 sig.setCustomTokenId(tokId);
-                sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS +
-                        WSConstants.SAML_ASSERTION_ID);
+                sig.setCustomTokenValueType(RampartUtil.getSAML10AssertionNamespace());
                 sig.setSecretKey(tok.getSecret());
                 sig.setSignatureAlgorithm(algorithmSuite.getAsymmetricSignature());
                 sig.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
@@ -414,10 +444,11 @@ public class TransportBindingBuilder ext
                         rmd.getSecHeader());
 
                 sig.setParts(sigParts);
-                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+                List<javax.xml.crypto.dsig.Reference> referenceList
+                        = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
 
                 //Do signature
-                sig.computeSignature();
+                sig.computeSignature(referenceList);
 
                 //Add elements to header
                 this.setInsertionLocation(RampartUtil.insertSiblingAfter(
@@ -464,7 +495,7 @@ public class TransportBindingBuilder ext
             tokenIncluded = true;
         }
 
-        Vector sigParts = new Vector();
+        List<WSEncryptionPart> sigParts = new ArrayList<WSEncryptionPart>();
         
         if(this.timestampElement != null){
             sigParts.add(new WSEncryptionPart(rmd.getTimestampId()));                          
@@ -482,9 +513,9 @@ public class TransportBindingBuilder ext
             }
     
             ArrayList headers = signdParts.getHeaders();
-            for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
-                Header header = (Header) iterator.next();
-                WSEncryptionPart wep = new WSEncryptionPart(header.getName(), 
+            for (Object objectHeader : headers) {
+                Header header = (Header) objectHeader;
+                WSEncryptionPart wep = new WSEncryptionPart(header.getName(),
                         header.getNamespace(),
                         "Content");
                 sigParts.add(wep);
@@ -502,7 +533,7 @@ public class TransportBindingBuilder ext
               
               // Setting the AttachedReference or the UnattachedReference according to the flag
               OMElement ref;
-              if (tokenIncluded == true) {
+              if (tokenIncluded) {
                   ref = tok.getAttachedReference();
               } else {
                   ref = tok.getUnattachedReference();
@@ -520,18 +551,24 @@ public class TransportBindingBuilder ext
               dkSign.setDerivedKeyLength(algorithmSuite.getSignatureDerivedKeyLength());
               
               dkSign.prepare(doc);
-              
+
+              /**
+               * Add <wsc:DerivedKeyToken>..</wsc:DerivedKeyToken> to security
+               * header. We need to add this just after Encrypted Key and just before <Signature>..</Signature>
+               * elements. (As a convention)
+               */
               dkSign.appendDKElementToHeader(rmd.getSecHeader());
               
               dkSign.setParts(sigParts);
               
-              dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
+              List<Reference> referenceList
+                      = dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());
               
               //Do signature
-              dkSign.computeSignature();
-              
-              dkSign.appendSigToHeader(rmd.getSecHeader());
-              
+              dkSign.computeSignature(referenceList, false, null);
+
+              //this.appendToHeader(rmd.getSecHeader(), dkSign.getSignatureElement());
+
               return dkSign.getSignatureValue();
               
           } catch (ConversationException e) {
@@ -547,8 +584,7 @@ public class TransportBindingBuilder ext
                 WSSecSignature sig = new WSSecSignature();
                 sig.setWsConfig(rmd.getConfig());
                 sig.setCustomTokenId(tok.getId().substring(1));
-                sig.setCustomTokenValueType(WSConstants.WSS_SAML_NS +
-                        WSConstants.SAML_ASSERTION_ID);
+                sig.setCustomTokenValueType(RampartUtil.getSAML10AssertionNamespace());
                 sig.setSecretKey(tok.getSecret());
                 sig.setSignatureAlgorithm(algorithmSuite.getAsymmetricSignature());
                 sig.setSignatureAlgorithm(algorithmSuite.getSymmetricSignature());
@@ -558,16 +594,14 @@ public class TransportBindingBuilder ext
                         rmd.getSecHeader());
 
                 sig.setParts(sigParts);
-                sig.addReferencesToSign(sigParts, rmd.getSecHeader());
+                List<Reference> referenceList
+                        = sig.addReferencesToSign(sigParts, rmd.getSecHeader());
 
                 //Do signature
-                sig.computeSignature();
+                sig.computeSignature(referenceList, false, this.getInsertionLocation());
 
                 //Add elements to header
-                this.setInsertionLocation(RampartUtil.insertSiblingAfter(
-                        rmd,
-                        this.getInsertionLocation(),
-                        sig.getSignatureElement()));
+                this.setInsertionLocation(sig.getSignatureElement());
 
                 return sig.getSignatureValue();
 

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/errors.properties
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/errors.properties?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/errors.properties (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/errors.properties Thu Mar  1 09:54:05 2012
@@ -77,7 +77,9 @@ cannotValidateTimestamp = The timestamp 
 trustVerificationError = The certificate used for the signature is not trusted
 cannotFindAliasForCert = Could not get alias for certificate with {0}
 noCertForAlias = Could not get certificates for alias  {0}
+noCertForSubject = Could not get certificates for subject  {0}
 certPathVerificationFailed = Certificate path verification failed for certificate with subject
+noCertificatesForIssuer = No certificates were found for issuer \"{0}\" and issuer serial number \"{1}\"
 
 #Rampart Results Validation Errors
 timestampMissing = Missing Timestamp
@@ -98,4 +100,5 @@ invalidTransport = Expected transport is
 requiredElementsMissing = Required Elements not found in the incoming message : {0}
 repeatingNonceValue = Nonce value : {0}, already seen before for user name : {1}. Possibly this could be a replay attack.
 invalidNonceLifeTime = Invalid value for nonceLifeTime in rampart configuration file.
-invalidIssuerAddress = Invalid value for Issuer
\ No newline at end of file
+invalidIssuerAddress = Invalid value for Issuer
+invalidSignatureAlgo=Invalid signature algorithm for Asymmetric binding
\ No newline at end of file

Added: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/CertificateValidator.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/CertificateValidator.java?rev=1295489&view=auto
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/CertificateValidator.java (added)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/CertificateValidator.java Thu Mar  1 09:54:05 2012
@@ -0,0 +1,45 @@
+/*
+ * Copyright 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.rampart.handler;
+
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.validate.SignatureTrustValidator;
+
+import java.security.cert.X509Certificate;
+
+/**
+ * Validates the certificate in a signature.
+ */
+public class CertificateValidator extends SignatureTrustValidator {
+
+    CertificateValidator() {
+
+    }
+
+    /**
+     * Checks the validity of the given certificate. For more info see SignatureTrustValidator.verifyTrustInCert.
+     * @param certificate Certificate to be validated.
+     * @param signatureCrypto Signature crypto instance.
+     * @return true if certificate used in signature is valid. False if it is not valid.
+     * @throws WSSecurityException If an error occurred while trying to access Crypto and Certificate properties.
+     */
+    boolean validateCertificate(X509Certificate certificate, Crypto signatureCrypto) throws WSSecurityException {
+        return verifyTrustInCert(certificate, signatureCrypto, false);
+    }
+
+}

Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/PostDispatchVerificationHandler.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/PostDispatchVerificationHandler.java?rev=1295489&r1=1295488&r2=1295489&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/PostDispatchVerificationHandler.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-core/src/main/java/org/apache/rampart/handler/PostDispatchVerificationHandler.java Thu Mar  1 09:54:05 2012
@@ -37,10 +37,10 @@ import org.apache.ws.secpolicy.model.Bin
 import org.apache.ws.secpolicy.model.SupportingToken;
 import org.apache.ws.security.WSConstants;
 import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.handler.WSHandlerResult;
 
 import java.util.Iterator;
 import java.util.List;
-import java.util.Vector;
 
 /**
  * Handler to verify the message security after dispatch
@@ -174,7 +174,7 @@ public class PostDispatchVerificationHan
             if(msgContext.getProperty(WSHandlerConstants.RECV_RESULTS) == null) {
                     throw new AxisFault("InvalidSecurity");
             } else {
-                if(((Vector)msgContext.getProperty(WSHandlerConstants.RECV_RESULTS)).size() == 0) {
+                if(((List<WSHandlerResult>)msgContext.getProperty(WSHandlerConstants.RECV_RESULTS)).size() == 0) {
                     throw new AxisFault("InvalidSecurity");
                 }
             }