You are viewing a plain text version of this content. The canonical link for it is here.
Posted to wss4j-dev@ws.apache.org by ru...@apache.org on 2006/02/05 21:49:51 UTC

svn commit: r375103 - in /webservices/wss4j/trunk: src/org/apache/ws/security/ src/org/apache/ws/security/conversation/ src/org/apache/ws/security/conversation/dkalgo/ src/org/apache/ws/security/message/ src/org/apache/ws/security/message/token/ src/or...

Author: ruchithf
Date: Sun Feb  5 12:49:49 2006
New Revision: 375103

URL: http://svn.apache.org/viewcvs?rev=375103&view=rev
Log:

- Implemented encrypting a message using a DerivedKey (Signature coming up :-) )
	- Added WSSecDKSignEncrypt to do the Encryption and Signing (Sometimes the same session key will have to be used to derive the encryption and signature key therefore thought of using a single builder to do both if and when required)
	- Added a new processor to process derived keys : DerivedKeyTokenProcessor

	- Imported (slightly refactored) a set of classes from secure conversation sandbox, which are required for key derivation and to access constants

- Added a test case - wssec.TestWSSecurityNewDK

- Fixed a test compile error by adding two empty methods to WSS4JPolicyToken


		

Added:
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSignEncrypt.java
    webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java   (with props)
    webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
    webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java
Modified:
    webservices/wss4j/trunk/src/org/apache/ws/security/WSConstants.java
    webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java
    webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java
    webservices/wss4j/trunk/src/org/apache/ws/security/policy/WSS4JPolicyToken.java
    webservices/wss4j/trunk/src/org/apache/ws/security/processor/ReferenceListProcessor.java
    webservices/wss4j/trunk/src/org/apache/ws/security/util/WSSecurityUtil.java
    webservices/wss4j/trunk/test/wssec/PackageTests.java

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSConstants.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSConstants.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSConstants.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSConstants.java Sun Feb  5 12:49:49 2006
@@ -33,7 +33,7 @@
     public static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
     public static final String WSSE11_NS = "http://docs.oasis-open.org/wss/2005/xx/oasis-2005xx-wss-wssecurity-secext-1.1.xsd";
     public static final String WSU_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
-
+    
     /*
      * The base UIRs for the various profiles.
      */
@@ -97,7 +97,7 @@
     public static final String SIGNATURE_CONFIRMATION_LN = "SignatureConfirmation"; 
     public static final String SALT_LN = "Salt";
     public static final String ITERATION_LN = "Iteration";
-
+    
     /*
      * The definitions for SAML
      */
@@ -372,5 +372,25 @@
     public static final int WSE_DERIVED_KEY_LEN = 16;
     public static final String LABEL_FOR_DERIVED_KEY = "WS-Security";
     
+//    public interface WSC {
+//        /*
+//         * WS-secureConversation namespace
+//         */
+//        public static final String WSC_NS = "http://schemas.xmlsoap.org/ws/2005/02/sc";
+//        
+//        /*
+//         * The local names and attribute names used by WSC
+//         */
+//        public final static String DERIVED_KEY_LN = "DerivedKeyToken";
+//        public final static String ALGORITHM_LN = "Algorithm";
+//        public final static String PROPERTIES_LN = "Properties";
+//        public final static String GENERATION_LN = "Generation";
+//        public final static String OFFSET_LN = "Offset";
+//        public final static String LENGTH_LN = "Length";
+//        public final static String LABEL_LN = "Label";
+//
+//        public final static String P_SHA_1 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1";
+//    }
+
 }
 

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSSConfig.java Sun Feb  5 12:49:49 2006
@@ -242,6 +242,8 @@
             name = "org.apache.ws.security.processor.ReferenceListProcessor";
         } else if (el.equals(WSSecurityEngine.signatureConfirmation)) {
             name = "org.apache.ws.security.processor.SignatureConfirmationProcessor";
+        } else if (el.equals(WSSecurityEngine.DERIVED_KEY_TOKEN)) {
+            name = "org.apache.ws.security.processor.DerivedKeyTokenProcessor";
         }
 
         if(name != null){

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/WSSecurityEngine.java Sun Feb  5 12:49:49 2006
@@ -20,6 +20,7 @@
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.conversation.ConversationConstants;
 import org.apache.ws.security.message.token.UsernameToken;
 import org.apache.ws.security.processor.Processor;
 import org.apache.ws.security.util.WSSecurityUtil;
@@ -30,6 +31,7 @@
 
 import javax.security.auth.callback.CallbackHandler;
 import javax.xml.namespace.QName;
+
 import java.util.Vector;
 
 /**
@@ -82,6 +84,11 @@
      * <code>saml:Assertion</code> as defined by SAML specification
      */
     public static final QName SAML_TOKEN = new QName(WSConstants.SAML_NS, WSConstants.ASSERTION_LN);
+
+    /**
+     * <code>wsc:DerivedKeyToken</code> as defined by WS-SecureConversation specification
+     */
+    public static final QName DERIVED_KEY_TOKEN = new QName(ConversationConstants.WSC_NS, ConversationConstants.DERIVED_KEY_TOKEN_LN);
 
     public WSSecurityEngine() {
     }

Added: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,123 @@
+/*
+ * Copyright  2003-2005 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+package org.apache.ws.security.conversation;
+
+/**
+ * Class ConversationConstants
+ */
+public class ConversationConstants {
+
+	private static final String NS_YEAR_PREFIX = "http://schemas.xmlsoap.org/ws/2005/02/";
+	
+    /**
+     * WS-Secure Conversation namespace
+     */
+    public final static String WSC_NS = NS_YEAR_PREFIX + "sc";
+    
+    /**
+     * TOken type of DerivedKeyToken
+     */
+    public final static String TOKEN_TYPE_DERIVED_KEY_TOKEN = WSC_NS + "/dk";
+    
+    /**
+     * Token type of SecurityContextToken
+     */
+    public static final String TOKEN_TYPE_SECURITY_CONTEXT_TOKEN = WSC_NS  + "/sct";
+    
+    /**
+     * Field WSC_PREFIX
+     */
+    public final static String WSC_PREFIX = "wsc";
+
+    /**
+     * Field SECURITY_CONTEXT_TOKEN_LN
+     */
+    public static final String SECURITY_CONTEXT_TOKEN_LN =
+            "SecurityContextToken";
+
+    /**
+     * Field IDENTIFIER_LN
+     */
+    public static final String IDENTIFIER_LN = "Identifier";
+
+    /**
+     * Field EXPIRES_LN
+     */
+    public static final String EXPIRES_LN = "Expires";
+
+    /**
+     * Field KEYS_LN
+     */
+    public static final String KEYS_LN = "Keys";
+
+    /**
+     * Field SECURITY_TOKEN_REFERENCE_LN
+     */
+    public static final String SECURITY_TOKEN_REFERENCE_LN =
+            "SecurityTokenReference";
+
+    /**
+     * Field DERIVED_KEY_TOKEN_LN
+     */
+    public static final String DERIVED_KEY_TOKEN_LN = "DerivedKeyToken";
+
+    /**
+     * Field PROPERTIES_LN
+     */
+    public static final String PROPERTIES_LN = "Properties";
+
+    /**
+     * Field LENGTH_LN
+     */
+    public static final String LENGTH_LN = "Length";
+
+    /**
+     * Field GENERATION_LN
+     */
+    public static final String GENERATION_LN = "Generation";
+
+    /**
+     * Field OFFSET_LN
+     */
+    public static final String OFFSET_LN = "Offset";
+
+    /**
+     * Field LABEL_LN
+     */
+    public static final String LABEL_LN = "Label";
+
+    /**
+     * Field NONCE_LN
+     */
+    public static final String NONCE_LN = "Nonce";
+
+    public static final int DIRECT_GENERATED = 1;
+    public static final int STS_GENERATED = 2;
+    public static final int STSREQUEST_TOKEN = 3;
+    public static final int INTEROP_SCENE1 = 4;
+
+    public static final String IDENTIFIER = "SCT_Identifier";
+
+    public static final int DK_SIGN = 1;
+    public static final int DK_ENCRYPT = 2;
+    
+    public final static String DEFAULT_LABEL = "WS-SecureConversation";
+    
+    public interface DerivationAlgorithm {
+        public final static String P_SHA_1 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1";
+    }
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationConstants.java
------------------------------------------------------------------------------
    svn:executable = *

Added: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,31 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+package org.apache.ws.security.conversation;
+
+import org.apache.ws.security.WSSecurityException;
+
+public class ConversationException extends WSSecurityException {
+
+    /**
+     * Constructor ConversationException
+     *
+     * @param message
+     */
+    public ConversationException(String message) {
+        super(message);
+    }
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/ConversationException.java
------------------------------------------------------------------------------
    svn:executable = *

Added: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,46 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.conversation.dkalgo;
+
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.conversation.ConversationException;
+
+/**
+ * @author Ruchith Fernando
+ */
+
+public class AlgoFactory {
+
+    /**
+     * This gives a DerivationAlgorithm instance from the default set of algorithms provided
+     *
+     * @param algorithm The algo identifier @see DeivationAlgorithm
+     * @return A derivatio algorithm
+     * @throws ConversationException If the specified algorithmis not available in
+     *                               default implementations
+     */
+    public static DerivationAlgorithm getInstance(String algorithm) throws
+            ConversationException {
+        if (algorithm.equals(ConversationConstants.DerivationAlgorithm.P_SHA_1)) {
+            return new P_SHA1();
+        } else {
+            throw new ConversationException("No such algorithm");
+        }
+    }
+
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/AlgoFactory.java
------------------------------------------------------------------------------
    svn:executable = *

Added: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,30 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.conversation.dkalgo;
+
+import org.apache.ws.security.conversation.ConversationException;
+
+/**
+ *
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public interface DerivationAlgorithm {
+
+    public byte[] createKey(byte[] secret, byte[] seed, int offset,
+            long length) throws ConversationException;
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/DerivationAlgorithm.java
------------------------------------------------------------------------------
    svn:executable = *

Added: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,108 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.conversation.dkalgo;
+
+/**
+ *
+ <pre>
+ P_SHA-1 DEFINITION
+ ==================
+ <b>P_SHA-1(secret, seed)</b> =
+ HMAC_SHA-1(secret, A(1) + seed) +
+ HMAC_SHA-1(secret, A(2) + seed) +
+ HMAC_SHA-1(secret, A(3) + seed) + ...
+ <i>Where + indicates concatenation.</i>
+ <br>
+ A() is defined as:
+ A(0) = seed
+ A(i) = HMAC_SHA-1(secret, A(i-1))
+ <br>
+ <i>Source : RFC 2246 - The TLS Protocol Version 1.0
+ Section 5. HMAC and the pseudorandom function</i>
+ </pre>
+ *
+ * @author Ruchith Fernando
+ */
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.ws.security.conversation.ConversationException;
+
+public class P_SHA1
+        implements DerivationAlgorithm {
+
+    public byte[] createKey(byte[] secret, byte[] seed, int offset,
+            long length) throws ConversationException {
+        try {
+            Mac mac = Mac.getInstance("HmacSHA1");
+
+            byte[] tempBytes = P_hash(secret, seed, mac,
+                    (offset + (int) length));
+
+            byte[] key = new byte[(int) length];
+
+            for (int i = 0; i < key.length; i++)
+                key[i] = tempBytes[i + offset];
+
+            return key;
+        } catch (Exception ex) {
+            throw new ConversationException("Key Derivation : P_SHA-1: "
+                    + ex.getMessage());
+        }
+    }
+    
+    /**
+     * From WSUsernameToken  :-)
+     *
+     * @param secret
+     * @param seed
+     * @param mac
+     * @param required
+     * @return
+     * @throws java.lang.Exception
+     */
+    private static byte[] P_hash(byte[] secret, byte[] seed, Mac mac,
+                                 int required) throws Exception {
+        byte[] out = new byte[required];
+        int offset = 0, tocpy;
+        byte[] A, tmp;
+        A = seed;
+        while (required > 0) {
+            SecretKeySpec key = new SecretKeySpec(secret, "HMACSHA1");
+            mac.init(key);
+            mac.update(A);
+            A = mac.doFinal();
+            mac.reset();
+            mac.init(key);
+            mac.update(A);
+            mac.update(seed);
+            tmp = mac.doFinal();
+            tocpy = min(required, tmp.length);
+            System.arraycopy(tmp, 0, out, offset, tocpy);
+            offset += tocpy;
+            required -= tocpy;
+        }
+        return out;
+    }
+
+    private static int min(int a, int b) {
+        return (a > b) ? b : a;
+    }
+
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/conversation/dkalgo/P_SHA1.java
------------------------------------------------------------------------------
    svn:executable = *

Added: webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSignEncrypt.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSignEncrypt.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSignEncrypt.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSignEncrypt.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,436 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.message;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.util.Vector;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.SecretKey;
+
+import org.apache.axis.encoding.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.SOAPConstants;
+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.components.crypto.Crypto;
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.conversation.dkalgo.AlgoFactory;
+import org.apache.ws.security.conversation.dkalgo.DerivationAlgorithm;
+import org.apache.ws.security.message.token.BinarySecurity;
+import org.apache.ws.security.message.token.DerivedKeyToken;
+import org.apache.ws.security.message.token.Reference;
+import org.apache.ws.security.message.token.SecurityTokenReference;
+import org.apache.ws.security.message.token.X509Security;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.apache.xml.security.encryption.EncryptedData;
+import org.apache.xml.security.encryption.XMLCipher;
+import org.apache.xml.security.encryption.XMLEncryptionException;
+import org.apache.xml.security.keys.KeyInfo;
+import org.apache.xml.security.keys.content.X509Data;
+import org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+/**
+ * Encrypts and signes parts of a message with derived keys derived from a
+ * symmetric key. This symmetric key will be included as an EncryptedKey
+ * 
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public class WSSecDKSignEncrypt extends WSSecBase {
+
+    private static Log log = LogFactory.getLog(WSSecEncrypt.class.getName());
+
+    private static Log tlog = LogFactory.getLog("org.apache.ws.security.TIME");
+
+    protected boolean doDebug = false;
+    
+    private Document doc;
+    
+    protected WSSConfig wssConfig = WSSConfig.getDefaultWSConfig();
+    
+    protected String symEncAlgo = WSConstants.AES_128;
+
+    protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
+    
+    protected String encrUser = null;
+    
+    private byte[] ephemeralKey;
+    
+    private byte[] derivedsigKey;
+    
+    private byte[] derivedEncrKey;
+
+    private Element xencEncryptedKey;
+
+    private String encKeyId = null;
+    
+    protected int keyIdentifierType = WSConstants.ISSUER_SERIAL;
+
+    private BinarySecurity bstToken = null;
+
+    private Element envelope;
+
+    public Document build(Document doc, Crypto crypto, WSSecHeader secHeader) throws Exception  {
+        
+        this.prepare(doc, crypto);
+        
+        /*
+         * Setup the encrypted key
+         */
+        WSSecurityUtil.prependChildElement(this.doc, secHeader
+                .getSecurityHeader(), xencEncryptedKey, false);
+        if (bstToken != null) {
+            WSSecurityUtil.prependChildElement(this.doc, secHeader
+                    .getSecurityHeader(), bstToken.getElement(), false);
+        }
+        
+        //Create the derived keys
+        //At this point figure out the key length accordng to teh symencAlgo
+        int offset = 0;
+        int length = WSSecurityUtil.getKeyLength(this.symEncAlgo);
+        byte[] label = ConversationConstants.DEFAULT_LABEL.getBytes("UTF-8");
+        byte[] nonce = generateNonce();
+        
+        byte[] seed = new byte[label.length + nonce.length];
+        System.arraycopy(label, 0, seed, 0, label.length);
+        System.arraycopy(nonce, 0, seed, label.length, nonce.length);
+        
+        DerivationAlgorithm algo = AlgoFactory.getInstance(ConversationConstants.DerivationAlgorithm.P_SHA_1);
+        
+        this.derivedEncrKey = algo.createKey(this.ephemeralKey, seed, offset, length);
+        
+        
+        //Add the DKTs
+        DerivedKeyToken dkt = new DerivedKeyToken(this.doc);
+        String dkId = "derivedKeyId-" + dkt.hashCode();
+        
+        dkt.setLength(length);
+        dkt.setNonce(Base64.encode(nonce));
+        dkt.setOffset(offset);
+        dkt.setID(dkId);
+        //Create the SecurityTokenRef to the Encrypted Key
+        SecurityTokenReference strEncKey = new SecurityTokenReference(this.doc);
+        Reference ref = new Reference(doc);
+        ref.setURI("#" + encKeyId);
+        strEncKey.setReference(ref);
+        dkt.setSecuityTokenReference(strEncKey);
+        WSSecurityUtil.appendChildElement(this.doc, secHeader
+                .getSecurityHeader(), dkt.getElement());
+        
+        
+        //Create the SecurityTokenRef to the DKT
+        SecurityTokenReference str = new SecurityTokenReference(this.doc);
+        Reference ref2 = new Reference(doc);
+        ref2.setURI("#" + dkId);
+        str.setReference(ref2);
+        KeyInfo keyInfo = new KeyInfo(doc);
+        keyInfo.addUnknownElement(str.getElement());
+        
+        Vector parts = new Vector();
+        SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
+        WSEncryptionPart encP = new WSEncryptionPart(soapConstants
+                .getBodyQName().getLocalPart(), soapConstants
+                .getEnvelopeURI(), "Content");
+        parts.add(encP);
+        Vector encDataRefs = doEncryption(this.doc, this.derivedEncrKey, keyInfo, parts);
+        
+        createDataRefList(doc, dkt.getElement(), encDataRefs, secHeader.getSecurityHeader());
+        
+        return this.doc;
+    }
+
+    private Vector doEncryption(Document doc, byte[] secretKey,
+            KeyInfo keyInfo, Vector references) throws Exception {
+
+        SecretKey key = WSSecurityUtil.prepareSecretKey(this.symEncAlgo, secretKey);
+        
+        
+        XMLCipher xmlCipher = null;
+        try {
+            String provider = wssConfig.getJceProviderId();
+            if (provider == null) {
+                xmlCipher = XMLCipher.getInstance(symEncAlgo);
+            } else {
+                xmlCipher = XMLCipher.getProviderInstance(symEncAlgo, provider);
+            }
+        } catch (XMLEncryptionException e3) {
+            throw new WSSecurityException(
+                    WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
+        }
+
+        Vector encDataRefs = new Vector();
+
+        for (int part = 0; part < references.size(); part++) {
+            WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);
+            String elemName = encPart.getName();
+            String nmSpace = encPart.getNamespace();
+            String modifier = encPart.getEncModifier();
+            /*
+             * Third step: get the data to encrypt.
+             */
+            Element body = (Element) WSSecurityUtil.findElement(envelope,
+                    elemName, nmSpace);
+            if (body == null) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noEncElement", new Object[] { "{" + nmSpace + "}"
+                                + elemName });
+            }
+
+            boolean content = modifier.equals("Content") ? true : false;
+            String xencEncryptedDataId = "EncDataId-" + body.hashCode();
+
+            /*
+             * Forth step: encrypt data, and set neccessary attributes in
+             * xenc:EncryptedData
+             */
+            try {
+                xmlCipher.init(XMLCipher.ENCRYPT_MODE, key);
+                EncryptedData encData = xmlCipher.getEncryptedData();
+                encData.setId(xencEncryptedDataId);
+                encData.setKeyInfo(keyInfo);
+                xmlCipher.doFinal(doc, body, content);
+            } catch (Exception e2) {
+                throw new WSSecurityException(
+                        WSSecurityException.FAILED_ENC_DEC, null, null, e2);
+            }
+            encDataRefs.add(new String("#" + xencEncryptedDataId));
+        }
+        return encDataRefs;
+    }
+
+    /**
+     * @return
+     */
+    private byte[] generateNonce() throws Exception {
+        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+        byte[] temp = new byte[16];
+        random.nextBytes(temp);
+        return temp;
+    }
+
+    public void prepare(Document doc, Crypto crypto)
+        throws WSSecurityException, NoSuchAlgorithmException {
+        
+        this.doc = doc;
+        
+        /*
+         * Set up the ephemeral key
+         */
+        this.ephemeralKey = getEphemeralKey();
+        
+        /*
+         * Get the certificate that contains the public key for the public key
+         * algorithm that will encrypt the generated symmetric (session) key.
+         */
+        X509Certificate remoteCert = null;
+
+        X509Certificate[] certs = crypto.getCertificates(encrUser);
+        if (certs == null || certs.length <= 0) {
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "invalidX509Data", new Object[] { "for Encryption" });
+        }
+        remoteCert = certs[0];
+        
+        String certUri = "EncCertId-" + remoteCert.hashCode();
+        Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo, wssConfig
+                .getJceProviderId());
+        try {
+            cipher.init(Cipher.ENCRYPT_MODE, remoteCert);
+        } catch (InvalidKeyException e) {
+            throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
+                    null, null, e);
+        }
+        
+        if (doDebug) {
+            log.debug("cipher blksize: " + cipher.getBlockSize()
+                    + ", symm key length: " + this.ephemeralKey.length);
+        }
+        if (cipher.getBlockSize() < this.ephemeralKey.length) {
+            throw new WSSecurityException(
+                    WSSecurityException.FAILURE,
+                    "unsupportedKeyTransp",
+                    new Object[] { "public key algorithm too weak to encrypt symmetric key" });
+        }
+        byte[] encryptedKey = null;
+        try {
+            encryptedKey = cipher.doFinal(this.ephemeralKey);
+        } catch (IllegalStateException e1) {
+            throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
+                    null, null, e1);
+        } catch (IllegalBlockSizeException e1) {
+            throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
+                    null, null, e1);
+        } catch (BadPaddingException e1) {
+            throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
+                    null, null, e1);
+        }
+        Text keyText = WSSecurityUtil.createBase64EncodedTextNode(doc,
+                encryptedKey);
+
+        /*
+         * Now we need to setup the EncryptedKey header block 1) create a
+         * EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
+         * element, this wraps the wsse:SecurityTokenReference 3) Create and set
+         * up the SecurityTokenReference according to the keyIdentifer parameter
+         * 4) Create the CipherValue element structure and insert the encrypted
+         * session key
+         */
+        xencEncryptedKey = createEnrcyptedKey(doc, keyEncAlgo);
+        encKeyId = "EncKeyId-" + xencEncryptedKey.hashCode();
+        xencEncryptedKey.setAttributeNS(null, "Id", encKeyId);
+
+        KeyInfo keyInfo = new KeyInfo(doc);
+
+        SecurityTokenReference secToken = new SecurityTokenReference(doc);
+
+        switch (keyIdentifierType) {
+        case WSConstants.X509_KEY_IDENTIFIER:
+            secToken.setKeyIdentifier(remoteCert);
+            break;
+
+        case WSConstants.SKI_KEY_IDENTIFIER:
+            secToken.setKeyIdentifierSKI(remoteCert, crypto);
+            break;
+
+        case WSConstants.THUMBPRINT_IDENTIFIER:
+            secToken.setKeyIdentifierThumb(remoteCert);
+            break;
+
+        case WSConstants.ISSUER_SERIAL:
+            XMLX509IssuerSerial data = new XMLX509IssuerSerial(doc, remoteCert);
+            X509Data x509Data = new X509Data(doc);
+            x509Data.add(data);
+            secToken.setX509IssuerSerial(x509Data);
+            break;
+
+        case WSConstants.BST_DIRECT_REFERENCE:
+            Reference ref = new Reference(doc);
+            ref.setURI("#" + certUri);
+            bstToken = new X509Security(doc);
+            ((X509Security) bstToken).setX509Certificate(remoteCert);
+            bstToken.setID(certUri);
+            ref.setValueType(bstToken.getValueType());
+            secToken.setReference(ref);
+            break;
+
+        default:
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "unsupportedKeyId");
+        }
+        
+        keyInfo.addUnknownElement(secToken.getElement());
+        WSSecurityUtil.appendChildElement(doc, xencEncryptedKey, keyInfo
+                .getElement());
+
+        Element xencCipherValue = createCipherValue(doc, xencEncryptedKey);
+        xencCipherValue.appendChild(keyText);
+
+        envelope = doc.getDocumentElement();
+        envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+                + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
+    }
+    
+
+    /**
+     * @return
+     */
+    private byte[] getEphemeralKey() throws NoSuchAlgorithmException {
+        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+        byte[] temp = new byte[16];
+        random.nextBytes(temp);
+        return temp;
+    }
+    
+    
+    /**
+     * Create DOM subtree for <code>xenc:EncryptedKey</code>
+     * 
+     * @param doc
+     *            the SOAP enevelope parent document
+     * @param keyTransportAlgo
+     *            specifies which alogrithm to use to encrypt the symmetric key
+     * @return an <code>xenc:EncryptedKey</code> element
+     */
+    public static Element createEnrcyptedKey(Document doc,
+            String keyTransportAlgo) {
+        Element encryptedKey = doc.createElementNS(WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX + ":EncryptedKey");
+
+        WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX);
+        Element encryptionMethod = doc.createElementNS(WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX + ":EncryptionMethod");
+        encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo);
+        WSSecurityUtil.appendChildElement(doc, encryptedKey, encryptionMethod);
+        return encryptedKey;
+    }
+    
+    public static Element createCipherValue(Document doc, Element encryptedKey) {
+        Element cipherData = doc.createElementNS(WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX + ":CipherData");
+        Element cipherValue = doc.createElementNS(WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX + ":CipherValue");
+        cipherData.appendChild(cipherValue);
+        WSSecurityUtil.appendChildElement(doc, encryptedKey, cipherData);
+        return cipherValue;
+    }
+    
+
+    public void setEncryptionUser(String user) {
+        this.encrUser = user;
+    }
+    
+    public static Element createDataRefList(Document doc, Element dktElem,
+            Vector encDataRefs, Element secHeader) {
+        Element referenceList = doc.createElementNS(WSConstants.ENC_NS,
+                WSConstants.ENC_PREFIX + ":ReferenceList");
+        for (int i = 0; i < encDataRefs.size(); i++) {
+            String dataReferenceUri = (String) encDataRefs.get(i);
+            Element dataReference = doc.createElementNS(WSConstants.ENC_NS,
+                    WSConstants.ENC_PREFIX + ":DataReference");
+            dataReference.setAttributeNS(null, "URI", dataReferenceUri);
+            referenceList.appendChild(dataReference);
+        }
+        Node node = dktElem.getNextSibling();
+        if(node == null || (node != null && !(node instanceof Element))) {
+            //If (at this moment) DerivedKeyToken is the LAST element of 
+            //the security header 
+            secHeader.appendChild(referenceList);
+        } else {
+            secHeader.insertBefore(referenceList, node);
+        }
+        return referenceList;
+    }
+
+    public void setSymmetricEncAlgorithm(String algo) {
+        symEncAlgo = algo;
+    }
+
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,454 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+package org.apache.ws.security.message.token;
+
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import javax.xml.namespace.QName;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.conversation.ConversationException;
+import org.apache.ws.security.util.DOM2Writer;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+
+/**
+ <DerivedKeyToken wsu:Id="..." wsc:Algorithm="...">
+ <SecurityTokenReference>...</SecurityTokenReference>
+ <Properties>...</Properties>
+ <Generation>...</Generation>
+ <Offset>...</Offset>
+ <Length>...</Length>
+ <Label>...</Label>
+ <Nonce>...</Nonce>
+ </DerivedKeyToken>
+ */
+
+/**
+ * @author Ruchith Fernando
+ * @version 1.0
+ */
+public class DerivedKeyToken {
+
+    private Log log = LogFactory.getLog(DerivedKeyToken.class.getName());
+
+    public static final QName TOKEN = new QName(ConversationConstants.WSC_NS,
+            ConversationConstants.
+            DERIVED_KEY_TOKEN_LN);
+
+    //These are the elements that are used to create the SecurityContextToken
+    protected Element element = null;
+    protected Element elementSecurityTokenReference = null;
+    protected Element elementProperties = null;
+    protected Element elementGeneration = null;
+    protected Element elementOffset = null;
+    protected Element elementLength = null;
+    protected Element elementLabel = null;
+    protected Element elementNonce = null;
+
+    /**
+     * This will create an empty DerivedKeyToken
+     *
+     * @param doc THe DOM document
+     */
+    public DerivedKeyToken(Document doc) {
+        log.debug("DerivedKeyToken: created");
+        this.element = doc.createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" +
+                ConversationConstants.
+                DERIVED_KEY_TOKEN_LN);
+        WSSecurityUtil.setNamespace(this.element, ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+    }
+
+    /**
+     * This will create a DerivedKeyToken object with the given DErivedKeyToken element
+     *
+     * @param elem The DErivedKeyToken DOM element
+     * @throws WSSecurityException If the element is not a derived key token
+     */
+    public DerivedKeyToken(Element elem) throws WSSecurityException {
+        log.debug("DerivedKeyToken: created : element constructor");
+        this.element = elem;
+        QName el = new QName(this.element.getNamespaceURI(),
+                this.element.getLocalName());
+        if (!el.equals(TOKEN)) {
+            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN,
+                    "badTokenType00", new Object[]{el});
+        }
+        this.elementSecurityTokenReference = (Element) WSSecurityUtil.
+                getDirectChild(this.element,
+                        ConversationConstants.SECURITY_TOKEN_REFERENCE_LN,
+                        WSConstants.WSSE_NS);
+        this.elementProperties = (Element) WSSecurityUtil.getDirectChild(this.
+                element, ConversationConstants.PROPERTIES_LN,
+                ConversationConstants.WSC_NS);
+        this.elementGeneration = (Element) WSSecurityUtil.getDirectChild(this.
+                element, ConversationConstants.GENERATION_LN,
+                ConversationConstants.WSC_NS);
+        this.elementOffset = (Element) WSSecurityUtil.getDirectChild(this.element,
+                ConversationConstants.OFFSET_LN, ConversationConstants.WSC_NS);
+        this.elementLength = (Element) WSSecurityUtil.getDirectChild(this.element,
+                ConversationConstants.LENGTH_LN, ConversationConstants.WSC_NS);
+        this.elementLabel = (Element) WSSecurityUtil.getDirectChild(this.element,
+                ConversationConstants.LABEL_LN, ConversationConstants.WSC_NS);
+        this.elementNonce = (Element) WSSecurityUtil.getDirectChild(this.element,
+                ConversationConstants.NONCE_LN, ConversationConstants.WSC_NS);
+    }
+
+    /**
+     * Sets the security token reference of the derived key token
+     * This is the reference to the shared secret used in the conversation/context
+     *
+     * @param ref Security token reference
+     */
+    public void setSecuityTokenReference(SecurityTokenReference ref) {
+        this.elementSecurityTokenReference = ref.getElement();
+        //WSSecurityUtil.appendChildElement(doc, this.element, ref.getElement());
+        this.element.appendChild(ref.getElement());
+    }
+
+    /**
+     * Returns the SecurityTokenReference of the derived key token
+     *
+     * @return
+     * @throws WSSecurityException
+     */
+    public SecurityTokenReference getSecuityTokenReference() throws
+            WSSecurityException {
+        if (this.elementSecurityTokenReference != null) {
+            return new SecurityTokenReference(this.elementSecurityTokenReference);
+        }
+        return null;
+    }
+
+    //Write the getter for security token reference
+
+    /**
+     * This adds a property into
+     * /DerivedKeyToken/Properties
+     *
+     * @param propName  Name of the property
+     * @param propValue Value of the property
+     */
+    private void addProperty(String propName, String propValue) {
+        if (this.elementProperties == null) { //Create the properties element if it is not there
+            this.elementProperties = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                    "wsc:" +
+                    ConversationConstants.PROPERTIES_LN);
+            WSSecurityUtil.setNamespace(this.elementProperties,
+                    ConversationConstants.WSC_NS,
+                    WSConstants.WSSE_PREFIX);
+            this.element.appendChild(this.elementProperties);
+        }
+        Element tempElement = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" + propName);
+        tempElement.appendChild(this.element.getOwnerDocument().createTextNode(propValue));
+
+        this.elementProperties.appendChild(tempElement);
+    }
+
+    /**
+     * This is used to set the Name, Label and Nonce element values in the properties element
+     * <b>At this point I'm not sure if these are the only properties that will appear in the
+     * <code>Properties</code> element. There fore this method is provided
+     * If this is not required feel free to remove this :D
+     * </b>
+     *
+     * @param name  Value of the Properties/Name element
+     * @param label Value of the Properties/Label element
+     * @param nonce Value of the Properties/Nonce element
+     */
+    public void setProperties(String name, String label,
+                              String nonce) {
+        Hashtable table = new Hashtable(3);
+        table.put("Name", name);
+        table.put("Label", label);
+        table.put("Nonce", nonce);
+        this.setProperties(table);
+    }
+
+    /**
+     * If there are other types of properties other than Name, Label and Nonce
+     * This is provided for extensibility purposes
+     *
+     * @param properties The properties and values in a hashtable
+     */
+    public void setProperties(Hashtable properties) {
+        Enumeration keys = properties.keys();
+        while (keys.hasMoreElements()) {
+            String propertyName = (String) keys.nextElement(); //Get the property name
+            //Check whether this property is already there
+            //If so change the value
+            Node node = WSSecurityUtil.findElement(this.elementProperties,
+                    propertyName,
+                    ConversationConstants.WSC_NS);
+            if (node != null && node instanceof Element) { //If the node is not null
+                Text node1 = getFirstNode((Element) node);
+                node1.setData((String) properties.get(propertyName));
+            } else {
+                this.addProperty(propertyName,
+                        (String) properties.get(propertyName));
+            }
+        }
+    }
+
+    public Hashtable getProperties() {
+        if (this.elementProperties != null) {
+            Hashtable table = new Hashtable();
+            NodeList nodes = this.elementProperties.getChildNodes();
+            for (int i = 0; i < nodes.getLength(); i++) {
+                Node tempNode = nodes.item(i);
+                if (tempNode instanceof Element) {
+                    Text text = this.getFirstNode((Element) tempNode);
+                    table.put(tempNode.getNodeName(), text.getData());
+                }
+            }
+
+        }
+        return null;
+    }
+
+    /**
+     * Sets the length of the derived key
+     *
+     * @param length The length of the derived key as a long
+     */
+    public void setLength(int length) {
+        this.elementLength = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" +
+                ConversationConstants.LENGTH_LN);
+        WSSecurityUtil.setNamespace(this.elementLength,
+                ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+        this.elementLength.appendChild(this.element.getOwnerDocument().createTextNode(Long.toString(length)));
+        this.element.appendChild(this.elementLength);
+    }
+
+    public int getLength() {
+        if (this.elementLength != null) {
+            return Integer.parseInt(getFirstNode(this.elementLength).getData());
+        }
+        return -1;
+    }
+
+    /**
+     * Sets the offset
+     *
+     * @param offset The offset value as an integer
+     */
+    public void setOffset( int offset) throws ConversationException {
+        //This element MUST NOT be used if the <Generation> element is specified
+        if (this.elementGeneration == null) {
+            this.elementOffset = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                    "wsc:" +
+                    ConversationConstants.OFFSET_LN);
+            WSSecurityUtil.setNamespace(this.elementOffset,
+                    ConversationConstants.WSC_NS,
+                    ConversationConstants.WSC_PREFIX);
+            this.elementOffset.appendChild(this.element.getOwnerDocument().createTextNode(Integer.toString(offset)));
+            this.element.appendChild(this.elementOffset);
+        } else {
+            throw new ConversationException("Offset cannot be set along with generation - generation is already set");
+        }
+
+    }
+
+    public int getOffset() {
+        if (this.elementOffset != null) {
+            return Integer.parseInt(getFirstNode(this.elementOffset).getData());
+        }
+        return -1;
+    }
+
+    /**
+     * Sets the generation of the derived key
+     *
+     * @param generation generation value as an integer
+     */
+    public void setGeneration(int generation) throws
+            ConversationException {
+        //This element MUST NOT be used if the <Offset> element is specified
+        if (this.elementOffset == null) {
+            this.elementGeneration = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                    "wsc:" + ConversationConstants.GENERATION_LN);
+            WSSecurityUtil.setNamespace(this.elementGeneration,
+                    ConversationConstants.WSC_NS,
+                    ConversationConstants.WSC_PREFIX);
+            this.elementGeneration.appendChild(this.element.getOwnerDocument().createTextNode(Integer.toString(generation)));
+            this.element.appendChild(this.elementGeneration);
+        } else {
+            throw new ConversationException("Generatation cannot be set along with offset - Offset is already set");
+        }
+    }
+
+    public int getGeneration() {
+        if (this.elementGeneration != null) {
+            return Integer.parseInt(getFirstNode(this.elementGeneration).getData());
+        }
+        return -1;
+    }
+
+    /**
+     * Sets the label of the derived key
+     *
+     * @param label Label value as a string
+     */
+    public void setLabel(String label) {
+        this.elementLabel = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" +
+                ConversationConstants.LABEL_LN);
+        WSSecurityUtil.setNamespace(this.elementLabel, ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+        this.elementLabel.appendChild(this.element.getOwnerDocument().createTextNode(label));
+        this.element.appendChild(this.elementLabel);
+    }
+
+    /**
+     * Sets the nonce value of the derived key
+     *
+     * @param nonce Nonce value as a string
+     */
+    public void setNonce(String nonce) {
+        this.elementNonce = this.element.getOwnerDocument().createElementNS(ConversationConstants.WSC_NS,
+                "wsc:" +
+                ConversationConstants.NONCE_LN);
+        WSSecurityUtil.setNamespace(this.elementNonce, ConversationConstants.WSC_NS,
+                ConversationConstants.WSC_PREFIX);
+        this.elementNonce.appendChild(this.element.getOwnerDocument().createTextNode(nonce));
+        this.element.appendChild(this.elementNonce);
+
+    }
+
+    /**
+     * Returns the label of the derived key token
+     *
+     * @return Label of the derived key token
+     */
+    public String getLabel() {
+        if (this.elementLabel != null) {
+            return getFirstNode(this.elementLabel).getData();
+        }
+        return null;
+    }
+
+    /**
+     * Return the nonce of the derived key token
+     *
+     * @return Nonce of the derived key token
+     */
+    public String getNonce() {
+        if (this.elementNonce != null) {
+            return getFirstNode(this.elementNonce).getData();
+        }
+        return null;
+    }
+
+    /**
+     * Returns the first text node of an element.
+     *
+     * @param e the element to get the node from
+     * @return the first text node or <code>null</code> if node
+     *         is null or is not a text node
+     */
+    private Text getFirstNode(Element e) {
+        Node node = e.getFirstChild();
+        return ((node != null) && node instanceof Text) ? (Text) node : null;
+    }
+
+    /**
+     * Returns the dom element of this <code>SecurityContextToken</code> object.
+     *
+     * @return the DerivedKeyToken element
+     */
+    public Element getElement() {
+        return this.element;
+    }
+
+    /**
+     * Returns the string representation of the token.
+     *
+     * @return a XML string representation
+     */
+    public String toString() {
+        return DOM2Writer.nodeToString((Node) this.element);
+    }
+
+    /**
+     * Gets the id.
+     *
+     * @return the value of the <code>wsu:Id</code> attribute of this
+     *         DerivedKeyToken
+     */
+    public String getID() {
+        return this.element.getAttributeNS(WSConstants.WSU_NS, "Id");
+    }
+
+    /**
+     * Set the id of this derived key token.
+     *
+     * @param id the value for the <code>wsu:Id</code> attribute of this
+     *           DerivgedKeyToken
+     */
+    public void setID(String id) {
+        String prefix = WSSecurityUtil.setNamespace(this.element,
+                WSConstants.WSU_NS,
+                WSConstants.WSU_PREFIX);
+        this.element.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
+    }
+
+    /**
+     * Gets the derivattion algorithm
+     *
+     * @return the value of the <code>wsc:Algorithm</code> attribute of this
+     *         DerivedKeyToken
+     */
+    public String getAlgorithm() {
+        String algo = this.element.getAttributeNS(ConversationConstants.WSC_NS,
+                "Algorithm");
+        if (algo == null || algo.equals("")) {
+            return ConversationConstants.DerivationAlgorithm.P_SHA_1;
+        } else {
+            return algo;
+        }
+    }
+
+    /**
+     * Set the derivattion algorithm of this derived key token.
+     *
+     * @param derivattion algorithm the value for the <code>wsu:Algorithm</code> attribute of this
+     *                    DerivgedKeyToken
+     */
+    public void setAlgorithm(String algo) {
+        String prefix = WSSecurityUtil.setNamespace(this.element,
+                ConversationConstants.WSC_NS,
+                ConversationConstants.
+                WSC_PREFIX);
+        this.element.setAttributeNS(ConversationConstants.WSC_NS,
+                prefix + ":Algorithm", algo);
+    }
+
+}

Propchange: webservices/wss4j/trunk/src/org/apache/ws/security/message/token/DerivedKeyToken.java
------------------------------------------------------------------------------
    svn:executable = *

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/policy/WSS4JPolicyToken.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/policy/WSS4JPolicyToken.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/policy/WSS4JPolicyToken.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/policy/WSS4JPolicyToken.java Sun Feb  5 12:49:49 2006
@@ -115,4 +115,20 @@
 	public ArrayList getSigParts() {
 		return sigParts;
 	}
+
+    /**
+     * @return
+     */
+    public int getEncKeyIdentifier() {
+        // TODO TODO
+        throw new UnsupportedOperationException("TODO");
+    }
+
+    /**
+     * @return
+     */
+    public int getSigKeyIdentifier() {
+        // TODO TODO
+        throw new UnsupportedOperationException("TODO");
+    }
 }

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,144 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.processor;
+
+import java.util.Vector;
+
+import javax.security.auth.callback.CallbackHandler;
+
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSSConfig;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.conversation.ConversationConstants;
+import org.apache.ws.security.conversation.dkalgo.AlgoFactory;
+import org.apache.ws.security.conversation.dkalgo.DerivationAlgorithm;
+import org.apache.ws.security.message.token.DerivedKeyToken;
+import org.apache.ws.security.message.token.Reference;
+import org.apache.ws.security.message.token.SecurityTokenReference;
+import org.apache.ws.security.util.Base64;
+import org.w3c.dom.Element;
+
+/**
+ *
+ * @author Ruchith Fernando (ruchith.fernando@gmail.com)
+ */
+public class DerivedKeyTokenProcessor implements Processor {
+
+    private String id;
+    private byte[] keyBytes;
+    
+    private byte[] secret;
+    private int length;
+    private int offset;
+    private byte[] nonce;
+    private String label;
+    private String algorithm;
+    
+    public void handleToken(Element elem, Crypto crypto, Crypto decCrypto,
+            CallbackHandler cb, WSDocInfo wsDocInfo, Vector returnResults,
+            WSSConfig config) throws WSSecurityException {
+        
+        //Deserialize the DKT
+        DerivedKeyToken dkt = new DerivedKeyToken(elem);
+        
+        this.extractSecret(wsDocInfo, dkt);
+        
+        String tempNonce = dkt.getNonce();
+        if(tempNonce == null) {
+            throw new WSSecurityException("Missing wsc:Nonce value");
+        }
+        this.nonce = Base64.decode(tempNonce);
+        
+        this.length = dkt.getLength();
+    
+        this.label = dkt.getLabel();
+        
+        this.algorithm = dkt.getAlgorithm();
+        
+        this.id = dkt.getID();
+
+        if(length > 0) {
+            this.deriveKey();
+        }
+    }
+
+    private void deriveKey() throws WSSecurityException{
+        try {
+            DerivationAlgorithm algo = AlgoFactory.getInstance(this.algorithm);
+            byte[] labelBytes = null;
+            if(label == null || (label != null && label.length() == 0)) {
+                labelBytes = ConversationConstants.DEFAULT_LABEL.getBytes("UTF-8");
+            } else {
+                labelBytes = this.label.getBytes("UTF-8");
+            }
+            
+            byte[] seed = new byte[labelBytes.length + nonce.length];
+            System.arraycopy(labelBytes, 0, seed, 0, labelBytes.length);
+            System.arraycopy(nonce, 0, seed, labelBytes.length, nonce.length);
+            
+            this.keyBytes = algo.createKey(this.secret, seed, offset, length);
+            
+        } catch (Exception e) {
+            throw new WSSecurityException(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * @param wsDocInfo
+     * @param dkt
+     * @throws WSSecurityException
+     */
+    private void extractSecret(WSDocInfo wsDocInfo, DerivedKeyToken dkt) throws WSSecurityException {
+        SecurityTokenReference str = dkt.getSecuityTokenReference();
+        if(str != null) {
+            Reference ref = str.getReference();
+            String uri = ref.getURI();
+            Processor processor = wsDocInfo.getProcessor(uri);
+            if(processor instanceof EncryptedKeyProcessor) {
+                this.secret = ((EncryptedKeyProcessor)processor).getDecryptedBytes();
+            }
+        }
+    }
+
+    /**
+     * Returns the wsu:Id of the DerivedKeyToken
+     * @see org.apache.ws.security.processor.Processor#getId()
+     */
+    public String getId() {
+        return this.id;
+    }
+
+    /**
+     * @return Returns the keyBytes.
+     */
+    public byte[] getKeyBytes() {
+        return keyBytes;
+    }
+    
+    /**
+     * Get the derived key bytes for a given length
+     * @return Returns the keyBytes.
+     */
+    public byte[] getKeyBytes(int length) throws WSSecurityException {
+        this.length = length;
+        this.deriveKey();
+        return keyBytes;
+    } 
+
+}

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/processor/ReferenceListProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/ReferenceListProcessor.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/ReferenceListProcessor.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/ReferenceListProcessor.java Sun Feb  5 12:49:49 2006
@@ -17,6 +17,11 @@
 
 package org.apache.ws.security.processor;
 
+import java.util.Vector;
+
+import javax.crypto.SecretKey;
+import javax.security.auth.callback.CallbackHandler;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.ws.security.WSConstants;
@@ -25,8 +30,8 @@
 import org.apache.ws.security.WSSecurityEngineResult;
 import org.apache.ws.security.WSSecurityException;
 import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.message.token.SecurityTokenReference;
 import org.apache.ws.security.message.token.Reference;
+import org.apache.ws.security.message.token.SecurityTokenReference;
 import org.apache.ws.security.util.WSSecurityUtil;
 import org.apache.xml.security.encryption.XMLCipher;
 import org.apache.xml.security.encryption.XMLEncryptionException;
@@ -34,10 +39,6 @@
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-import javax.crypto.SecretKey;
-import javax.security.auth.callback.CallbackHandler;
-import java.util.Vector;
-
 public class ReferenceListProcessor implements Processor {
 	private static Log log = LogFactory.getLog(ReferenceListProcessor.class
 			.getName());
@@ -213,12 +214,17 @@
 			String uri = reference.getURI();
 			String id = uri.substring(1);
 			Processor p = wsDocInfo.getProcessor(id);
-			if (p == null || !(p instanceof EncryptedKeyProcessor)) {
+			if (p == null || (!(p instanceof EncryptedKeyProcessor) && !(p instanceof DerivedKeyTokenProcessor))) {
 				throw new WSSecurityException(
 						WSSecurityException.FAILED_ENC_DEC, "unsupportedKeyId");
 			}
-			EncryptedKeyProcessor ekp = (EncryptedKeyProcessor) p;
-			decryptedData = ekp.getDecryptedBytes();
+			if(p instanceof EncryptedKeyProcessor) {
+    			EncryptedKeyProcessor ekp = (EncryptedKeyProcessor) p;
+    			decryptedData = ekp.getDecryptedBytes();
+            } else if(p instanceof DerivedKeyTokenProcessor) {
+                DerivedKeyTokenProcessor dkp = (DerivedKeyTokenProcessor) p;
+                decryptedData = dkp.getKeyBytes(WSSecurityUtil.getKeyLength(algorithm));
+            }
 		} else {
 			throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
 					"noReference");

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/util/WSSecurityUtil.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/util/WSSecurityUtil.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/util/WSSecurityUtil.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/util/WSSecurityUtil.java Sun Feb  5 12:49:49 2006
@@ -767,4 +767,23 @@
         }
         return doAction;
     }
+    
+    /**
+     * Returns the length of the key in # of bytes 
+     * @param algorithm
+     * @return
+     */
+    public static int getKeyLength(String algorithm) throws WSSecurityException {
+        if(algorithm.equals(WSConstants.TRIPLE_DES)) {
+            return 24;
+        } else if (algorithm.equals(WSConstants.AES_128)){
+            return 16;
+        } else if (algorithm.equals(WSConstants.AES_192)){
+            return 24;
+        } else if (algorithm.equals(WSConstants.AES_256)){
+            return 32;
+        } else {
+            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM);
+        }
+    }
 }

Modified: webservices/wss4j/trunk/test/wssec/PackageTests.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/test/wssec/PackageTests.java?rev=375103&r1=375102&r2=375103&view=diff
==============================================================================
--- webservices/wss4j/trunk/test/wssec/PackageTests.java (original)
+++ webservices/wss4j/trunk/test/wssec/PackageTests.java Sun Feb  5 12:49:49 2006
@@ -67,6 +67,11 @@
         suite.addTestSuite(TestWSSecurityST1.class);
         suite.addTestSuite(TestWSSecurityST2.class);
         suite.addTestSuite(TestWSSecurityST3.class);
+        suite.addTestSuite(TestWSSecurityNew15.class);
+        suite.addTestSuite(TestWSSecurityNew2.class);
+        suite.addTestSuite(TestWSSecurityNew5.class);
+        suite.addTestSuite(TestWSSecurityNew9.class);
+        suite.addTestSuite(TestWSSecurityNewDK.class);
         return suite;
     }
 

Added: webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java?rev=375103&view=auto
==============================================================================
--- webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java (added)
+++ webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java Sun Feb  5 12:49:49 2006
@@ -0,0 +1,199 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package wssec;
+
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.axis.Message;
+import org.apache.axis.MessageContext;
+import org.apache.axis.client.AxisClient;
+import org.apache.axis.configuration.NullProvider;
+import org.apache.axis.message.SOAPEnvelope;
+import org.apache.axis.utils.XMLUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSecurityEngine;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.components.crypto.CryptoFactory;
+import org.apache.ws.security.message.WSSecDKSignEncrypt;
+import org.apache.ws.security.message.WSSecHeader;
+import org.w3c.dom.Document;
+
+public class TestWSSecurityNewDK extends TestCase implements CallbackHandler {
+    private static Log log = LogFactory.getLog(TestWSSecurityNewDK.class);
+    static final String soapMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
+            "   <soapenv:Body>" +
+            "      <ns1:testMethod xmlns:ns1=\"uri:LogTestService2\"></ns1:testMethod>" +
+            "   </soapenv:Body>" +
+            "</soapenv:Envelope>";
+
+    static final WSSecurityEngine secEngine = new WSSecurityEngine();
+    static final Crypto crypto = CryptoFactory.getInstance("cryptoSKI.properties");
+    MessageContext msgContext;
+    Message message;
+
+    /**
+     * TestWSSecurity constructor
+     * <p/>
+     * 
+     * @param name name of the test
+     */
+    public TestWSSecurityNewDK(String name) {
+        super(name);
+    }
+
+    /**
+     * JUnit suite
+     * <p/>
+     * 
+     * @return a junit test suite
+     */
+    public static Test suite() {
+        return new TestSuite(TestWSSecurityNewDK.class);
+    }
+
+    /**
+     * Main method
+     * <p/>
+     * 
+     * @param args command line args
+     */
+    public static void main(String[] args) {
+        junit.textui.TestRunner.run(suite());
+    }
+
+    /**
+     * Setup method
+     * <p/>
+     * 
+     * @throws Exception Thrown when there is a problem in setup
+     */
+    protected void setUp() throws Exception {
+        AxisClient tmpEngine = new AxisClient(new NullProvider());
+        msgContext = new MessageContext(tmpEngine);
+        message = getSOAPMessage();
+    }
+
+    /**
+     * Constructs a soap envelope
+     * <p/>
+     * 
+     * @return soap envelope
+     * @throws Exception if there is any problem constructing the soap envelope
+     */
+    protected Message getSOAPMessage() throws Exception {
+        InputStream in = new ByteArrayInputStream(soapMsg.getBytes());
+        Message msg = new Message(in);
+        msg.setMessageContext(msgContext);
+        return msg;
+    }
+
+    /**
+     * Test encryption using a DerivedKeyToken using TRIPLEDES
+     * @throws Exception Thrown when there is any problem in signing or verification
+     */
+    public void testEncryptionDecryptionTRIPLEDES() throws Exception {
+        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+        WSSecDKSignEncrypt builder = new WSSecDKSignEncrypt();
+        builder.setEncryptionUser("wss4jcert");
+        builder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+        builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
+        Document doc = unsignedEnvelope.getAsDocument();
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        log.info("Before Encryption Triple DES....");
+        Document encryptedDoc = builder.build(doc, crypto, secHeader);
+        log.info("After Encryption Triple DES....");
+        String out = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
+        System.out.println(out);
+        verify(doc);
+    }
+
+    /**
+     * Test encryption using a DerivedKeyToken using AES128 
+     * @throws Exception Thrown when there is any problem in signing or verification
+     */
+     public void testEncryptionDecryptionAES128() throws Exception {
+        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+        WSSecDKSignEncrypt builder = new WSSecDKSignEncrypt();
+        builder.setEncryptionUser("wss4jcert");
+        builder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+        builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+        Document doc = unsignedEnvelope.getAsDocument();
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+        log.info("Before Encryption Triple AES_128....");
+        Document encryptedDoc = builder.build(doc, crypto, secHeader);
+        log.info("After Encryption Triple AES_128....");
+        Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(encryptedDoc);
+        if (log.isDebugEnabled()) {
+            log.debug("Encrypted message: 3DES  + DerivedKeys");
+            XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out));
+        }
+        String out = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
+        System.out.println(out);
+        verify(doc);
+    }
+    
+    /**
+     * Verifies the soap envelope
+     * <p/>
+     * 
+     * @param envelope 
+     * @throws Exception Thrown when there is a problem in verification
+     */
+    private void verify(Document doc) throws Exception {
+        secEngine.processSecurityHeader(doc, null, this, crypto);
+        SOAPUtil.updateSOAPMessage(doc, message);
+        String decryptedString = message.getSOAPPartAsString();
+        assertTrue(decryptedString.indexOf("LogTestService2") > 0 ? true : false);
+    }
+
+    public void handle(Callback[] callbacks)
+            throws IOException, UnsupportedCallbackException {
+        for (int i = 0; i < callbacks.length; i++) {
+            if (callbacks[i] instanceof WSPasswordCallback) {
+                WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+                /*
+                 * here call a function/method to lookup the password for
+                 * the given identifier (e.g. a user name or keystore alias)
+                 * e.g.: pc.setPassword(passStore.getPassword(pc.getIdentfifier))
+                 * for Testing we supply a fixed name here.
+                 */
+                pc.setPassword("security");
+            } else {
+                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
+            }
+        }
+    }
+}



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