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

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

Author: ruchithf
Date: Wed Mar  8 10:13:56 2006
New Revision: 384295

URL: http://svn.apache.org/viewcvs?rev=384295&view=rev
Log:
- Updated the DerivedKey related builders to be able to carryout signature and encryption based on a given ephmeral key and the identifier of the token to refer, to get the key information
- Added WSSecEncryptedKey builder - Main intention was to allow more flexible security header element ordering when using the _same_ ephmeral key (enclosed in an EncryptedKey) to carryout signature and encryption in any order. 
- Updated the test case with two more scenarios showing signature after encryption and encryption after signature


Added:
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecEncryptedKey.java
Modified:
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKEncrypt.java
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSign.java
    webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDerivedKeyBase.java
    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/message/WSSecDKEncrypt.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKEncrypt.java?rev=384295&r1=384294&r2=384295&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKEncrypt.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKEncrypt.java Wed Mar  8 10:13:56 2006
@@ -55,12 +55,11 @@
          */
         prepare(doc, crypto);
         
+        this.envelope =  doc.getDocumentElement();
         /*
          * prepend elements in the right order to the security header
          */
         prependDKElementToHeader(secHeader);
-        prependToHeader(secHeader);
-        prependBSTElementToHeader(secHeader);
                 
         SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
         if (parts == null) {

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSign.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSign.java?rev=384295&r1=384294&r2=384295&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSign.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDKSign.java Wed Mar  8 10:13:56 2006
@@ -106,8 +106,7 @@
          * prepend elements in the right order to the security header
          */
         prependDKElementToHeader(secHeader);
-        prependToHeader(secHeader);
-        prependBSTElementToHeader(secHeader);
+
         return doc;
     }
     

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDerivedKeyBase.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDerivedKeyBase.java?rev=384295&r1=384294&r2=384295&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDerivedKeyBase.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecDerivedKeyBase.java Wed Mar  8 10:13:56 2006
@@ -18,35 +18,19 @@
 package org.apache.ws.security.message;
 
 import java.io.UnsupportedEncodingException;
-import java.security.InvalidKeyException;
-import java.security.SecureRandom;
-import java.security.cert.X509Certificate;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
 
 import org.apache.axis.encoding.Base64;
-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.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.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.Text;
 
 /**
  * Base class for DerivedKey encryption and signature
@@ -57,25 +41,13 @@
  */
 public abstract class WSSecDerivedKeyBase extends WSSecBase {
     
-    private static Log log = LogFactory.getLog(WSSecDerivedKeyBase.class.getName());
-    
     protected Document document;
     
     /**
      * Session key used as the secret in key derivation
      */
     protected byte[] ephemeralKey;
-    
-    /**
-     * Remote user's alias to obtain the cert to encrypt the ephemeral key 
-     */
-    protected String encrUser = null;
-    
-    /**
-     * Algorithm used to encrypt the ephemeral key
-     */
-    protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
-    
+     
     /**
      * DerivedKeyToken of this builder
      */
@@ -91,27 +63,18 @@
      */
     protected String dktId = null;
     
-    /**
-     * xenc:EncryptedKey element
-     */
-    protected Element xencEncryptedKey = null;
 
-    /**
-     * Id value of the xenc:EncryptedKey element 
-     */
-    protected String encKeyId = null;
-    
-    /**
-     * BinarySecurityToken to be included in the case where BST_DIRECT_REFERENCE
-     * is used to refer to the asymm encryption cert
-     */
-    protected BinarySecurity bstToken = null;
     
     /**
      * soap:Envelope element
      */
     protected Element envelope = null;
     
+    /**
+     * The Token identifier of the token that the <code>DerivedKeyToken</code> 
+     * is (or to be) derived from.
+     */
+    protected String tokneIdentifier = null;
     
     /**
      * The derived key will change depending on the sig/encr algorithm.
@@ -125,28 +88,20 @@
     /**
      * @param ephemeralKey The ephemeralKey to set.
      */
-    public void setEphemeralKey(byte[] ephemeralKey) {
+    public void setExternalKey(byte[] ephemeralKey, 
+                                String tokenIdentifier) {
         this.ephemeralKey = ephemeralKey;
+        this.tokneIdentifier = tokenIdentifier;
     }
+
     
     /**
-     * Return the raw bytes of the ephemeral key
-     * @return
-     */
-    public byte[] getEphemeralKey() {
-        return this.ephemeralKey;
-    }
-    
-    /**
-     * Sets the alias of the remote cert which is usef to encrypt the ephemeral 
-     * key
-     * @param user
+     * @return Returns the tokneIdentifier.
      */
-    public void setEncryptionUser(String user) {
-        this.encrUser = user;
+    public String getTokneIdentifier() {
+        return tokneIdentifier;
     }
     
-    
     /**
      * Initialize a WSSec Derived key.
      * 
@@ -171,122 +126,7 @@
         throws WSSecurityException {
         
         document = doc;
-        
-        /*
-         * Set up the ephemeral key
-         */
-        this.ephemeralKey = generateEphemeralKey();
-        
-        /*
-         * 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);
-        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);
-        
         //Create the derived keys
         //At this point figure out the key length accordng to teh symencAlgo
         int offset = 0;
@@ -319,48 +159,13 @@
         //Create the SecurityTokenRef to the Encrypted Key
         SecurityTokenReference strEncKey = new SecurityTokenReference(document);
         Reference ref = new Reference(document);
-        ref.setURI("#" + encKeyId);
+        ref.setURI("#" + this.tokneIdentifier);
         strEncKey.setReference(ref);
         dkt.setSecuityTokenReference(strEncKey);
     }
 
-    
-    protected byte[] generateEphemeralKey() throws WSSecurityException {
-        try {
-            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
-            byte[] temp = new byte[16];
-            random.nextBytes(temp);
-            return temp;
-        } catch (Exception e) {
-            throw new WSSecurityException(
-                    "Error in creating the ephemeral key", e);
-        }
-    }
-    
-    protected 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;
-    }
-    
-    protected 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;
-    }
-    
+
     /**
      * Prepend the DerivedKey element to the elements already in the Security
      * header.
@@ -376,38 +181,5 @@
         WSSecurityUtil.prependChildElement(document, secHeader
             .getSecurityHeader(), dkt.getElement(), false);
     }
-    
-    /**
-     * Prepend the EncryptedKey element to the elements already in the Security
-     * header.
-     * 
-     * The method can be called any time after <code>prepare()</code>. This
-     * allows to insert the EncryptedKey element at any position in the Security
-     * header.
-     * 
-     * @param secHeader
-     *            The security header that holds the Signature element.
-     */
-    protected void prependToHeader(WSSecHeader secHeader) {
-        WSSecurityUtil.prependChildElement(document, secHeader
-                .getSecurityHeader(), xencEncryptedKey, false);
-    }
-    
-    /**
-     * Prepend the BinarySecurityToken to the elements already in the Security
-     * header.
-     * 
-     * The method can be called any time after <code>prepare()</code>. This
-     * allows to insert the BST element at any position in the Security header.
-     * 
-     * @param secHeader
-     *            The security header that holds the BST element.
-     */
-    protected void prependBSTElementToHeader(WSSecHeader secHeader) {
-        if (bstToken != null) {
-            WSSecurityUtil.prependChildElement(document, secHeader
-                    .getSecurityHeader(), bstToken.getElement(), false);
-        }
-        bstToken = null;
-    }
+
 }

Added: webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecEncryptedKey.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecEncryptedKey.java?rev=384295&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecEncryptedKey.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/message/WSSecEncryptedKey.java Wed Mar  8 10:13:56 2006
@@ -0,0 +1,350 @@
+/*
+ * 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.SecureRandom;
+import java.security.cert.X509Certificate;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+
+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.components.crypto.Crypto;
+import org.apache.ws.security.message.token.BinarySecurity;
+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.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.Text;
+
+/**
+ * Builder class to build an EncryptedKey.
+ * 
+ * This is expecially useful in the case where the same
+ * <code>EncryptedKey</code> has to be used to sign and encrypt the message In
+ * such a situation this builder will add the <code>EncryptedKey</code> to the
+ * security header and we can use the information form the builder to provide to
+ * other builders to reference to the token
+ */
+public class WSSecEncryptedKey extends WSSecBase {
+
+    private static Log log = LogFactory.getLog(WSSecEncryptedKey.class
+            .getName());
+    
+    protected boolean doDebug = false;
+    
+    protected Document document;
+    /**
+     * soap:Envelope element
+     */
+    protected Element envelope = null;
+    /**
+     * Session key used as the secret in key derivation
+     */
+    protected byte[] ephemeralKey;
+
+    /**
+     * Remote user's alias to obtain the cert to encrypt the ephemeral key
+     */
+    protected String encrUser = null;
+
+    /**
+     * Algorithm used to encrypt the ephemeral key
+     */
+    protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
+    
+    /**
+     * xenc:EncryptedKey element
+     */
+    protected Element encryptedKeyElement = null;
+
+    /**
+     * The Token identifier of the token that the <code>DerivedKeyToken</code> 
+     * is (or to be) derived from.
+     */
+    protected String tokneIdentifier = null;
+
+    /**
+     * BinarySecurityToken to be included in the case where BST_DIRECT_REFERENCE
+     * is used to refer to the asymm encryption cert
+     */
+    protected BinarySecurity bstToken = null;
+
+    
+    /**
+     * This will actually prepend the <code>EncryptedKey</code> to the 
+     * security header
+     * @param doc
+     * @param crypto
+     * @param secHeader
+     * @throws WSSecurityException
+     */
+    public void commit(Document doc, Crypto crypto, WSSecHeader secHeader)
+            throws WSSecurityException {
+        prependToHeader(secHeader);
+        prependBSTElementToHeader(secHeader);
+    }
+    
+    public void build(Document doc, Crypto crypto, WSSecHeader secHeader)
+            throws WSSecurityException {
+        prepare(doc, crypto);
+    }
+    
+    /**
+     * Prepare the ephemeralKey and the tokens required to be added to the 
+     * security header
+     * @param doc
+     * @param crypto
+     * @throws WSSecurityException
+     */
+    protected void prepare(Document doc, Crypto crypto)
+            throws WSSecurityException {
+
+        document = doc;
+
+        /*
+         * Set up the ephemeral key
+         */
+        if (this.ephemeralKey == null) {
+            this.ephemeralKey = generateEphemeralKey();
+        }
+
+        /*
+         * 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);
+        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
+         */
+        encryptedKeyElement = createEnrcyptedKey(doc, keyEncAlgo);
+        this.tokneIdentifier = "EncKeyId-" + encryptedKeyElement.hashCode();
+            encryptedKeyElement.setAttributeNS(null, "Id", this.tokneIdentifier);
+
+        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, encryptedKeyElement, keyInfo
+                .getElement());
+
+        Element xencCipherValue = createCipherValue(doc, encryptedKeyElement);
+        xencCipherValue.appendChild(keyText);
+
+        envelope = doc.getDocumentElement();
+        envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+                + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
+
+            
+    }
+    
+    /**
+     * Create an ephemeral key
+     * @return
+     * @throws WSSecurityException
+     */
+    protected byte[] generateEphemeralKey() throws WSSecurityException {
+        try {
+            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+            byte[] temp = new byte[16];
+            random.nextBytes(temp);
+            return temp;
+        } catch (Exception e) {
+            throw new WSSecurityException(
+                    "Error in creating the ephemeral key", e);
+        }
+    }
+    
+    /**
+     * Sets the alias of the remote cert which is usef to encrypt the ephemeral 
+     * key
+     * @param user
+     */
+    public void setEncryptionUser(String user) {
+        this.encrUser = user;
+    }
+    
+    
+    protected 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;
+    }
+    
+    protected 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;
+    }
+    
+    /**
+     * Prepend the EncryptedKey element to the elements already in the Security
+     * header.
+     * 
+     * The method can be called any time after <code>prepare()</code>. This
+     * allows to insert the EncryptedKey element at any position in the Security
+     * header.
+     * 
+     * @param secHeader
+     *            The security header that holds the Signature element.
+     */
+    protected void prependToHeader(WSSecHeader secHeader) {
+        WSSecurityUtil.prependChildElement(document, secHeader
+                .getSecurityHeader(), encryptedKeyElement, false);
+    }
+    
+    /**
+     * Prepend the BinarySecurityToken to the elements already in the Security
+     * header.
+     * 
+     * The method can be called any time after <code>prepare()</code>. This
+     * allows to insert the BST element at any position in the Security header.
+     * 
+     * @param secHeader
+     *            The security header that holds the BST element.
+     */
+    protected void prependBSTElementToHeader(WSSecHeader secHeader) {
+        if (bstToken != null) {
+            WSSecurityUtil.prependChildElement(document, secHeader
+                    .getSecurityHeader(), bstToken.getElement(), false);
+        }
+        bstToken = null;
+    }
+
+
+    /**
+     * @return Returns the ephemeralKey.
+     */
+    public byte[] getEphemeralKey() {
+        return ephemeralKey;
+    }
+
+    /**
+     * @return Returns the tokneIdentifier.
+     */
+    public String getTokneIdentifier() {
+        return tokneIdentifier;
+    }
+    
+}

Modified: webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java?rev=384295&r1=384294&r2=384295&view=diff
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java (original)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/DerivedKeyTokenProcessor.java Wed Mar  8 10:13:56 2006
@@ -109,7 +109,7 @@
         if(str != null) {
             Reference ref = str.getReference();
             String uri = ref.getURI();
-            Processor processor = wsDocInfo.getProcessor(uri);
+            Processor processor = wsDocInfo.getProcessor(uri.substring(1));
             if(processor instanceof EncryptedKeyProcessor) {
                 this.secret = ((EncryptedKeyProcessor)processor).getDecryptedBytes();
             }

Modified: webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java?rev=384295&r1=384294&r2=384295&view=diff
==============================================================================
--- webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java (original)
+++ webservices/wss4j/trunk/test/wssec/TestWSSecurityNewDK.java Wed Mar  8 10:13:56 2006
@@ -46,6 +46,7 @@
 import org.apache.ws.security.components.crypto.CryptoFactory;
 import org.apache.ws.security.message.WSSecDKEncrypt;
 import org.apache.ws.security.message.WSSecDKSign;
+import org.apache.ws.security.message.WSSecEncryptedKey;
 import org.apache.ws.security.message.WSSecHeader;
 import org.apache.xml.security.signature.XMLSignature;
 import org.w3c.dom.Document;
@@ -122,23 +123,42 @@
 
     /**
      * Test encryption using a DerivedKeyToken using TRIPLEDES
-     * @throws Exception Thrown when there is any problem in signing or verification
+     * @throws Exception Thrown when there is any problem in signing or 
+     * verification
      */
     public void testEncryptionDecryptionTRIPLEDES() throws Exception {
         SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
-        WSSecDKEncrypt builder = new WSSecDKEncrypt();
-        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);
+
+        //EncryptedKey
+        WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+        encrKeyBuilder.setEncryptionUser("wss4jcert");
+        encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+        encrKeyBuilder.build(doc, crypto, secHeader);
+
+        //Key information from the EncryptedKey
+        byte[] ek = encrKeyBuilder.getEphemeralKey();
+        String tokneIdentifier = encrKeyBuilder.getTokneIdentifier();  
+        
+        //Derived key encryption
+        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+        encrBuilder.setExternalKey(ek, tokneIdentifier);
+        Document encryptedDoc = encrBuilder.build(doc, crypto, secHeader);
+        
+        encrKeyBuilder.commit(encryptedDoc, crypto, secHeader);
+        
+       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);
     }
 
     /**
@@ -146,21 +166,34 @@
      * @throws Exception Thrown when there is any problem in signing or verification
      */
      public void testEncryptionDecryptionAES128() throws Exception {
-        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
-        WSSecDKEncrypt builder = new WSSecDKEncrypt();
-        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....");
+         SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+         Document doc = unsignedEnvelope.getAsDocument();
+         WSSecHeader secHeader = new WSSecHeader();
+         secHeader.insertSecurityHeader(doc);
+
+         //EncryptedKey
+         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+         encrKeyBuilder.setEncryptionUser("wss4jcert");
+         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+         encrKeyBuilder.build(doc, crypto, secHeader);
+
+         //Key information from the EncryptedKey
+         byte[] ek = encrKeyBuilder.getEphemeralKey();
+         String tokneIdentifier = encrKeyBuilder.getTokneIdentifier();  
+         
+         //Derived key encryption
+         WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+         encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+         encrBuilder.setExternalKey(ek, tokneIdentifier);
+         Document encryptedDoc = encrBuilder.build(doc, crypto, secHeader);
+         
+         encrKeyBuilder.commit(encryptedDoc, crypto, secHeader);
+         
         Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(encryptedDoc);
         if (log.isDebugEnabled()) {
             log.debug("Encrypted message: 3DES  + DerivedKeys");
-            XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out));
+            XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope()
+                    .getAsDOM(), new PrintWriter(System.out));
         }
 //        String out = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
 //        System.out.println(out);
@@ -169,25 +202,132 @@
      
      public void testSignature() throws Exception {
          SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
-         WSSecDKSign builder = new WSSecDKSign();
-         builder.setEncryptionUser("wss4jcert");
-         builder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
-         builder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
          Document doc = unsignedEnvelope.getAsDocument();
          WSSecHeader secHeader = new WSSecHeader();
          secHeader.insertSecurityHeader(doc);
-         log.info("Before HMAC-SHA1 signature");
-         Document signedDoc = builder.build(doc, crypto, secHeader);
+
+         //EncryptedKey
+         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+         encrKeyBuilder.setEncryptionUser("wss4jcert");
+         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+         encrKeyBuilder.build(doc, crypto, secHeader);
+
+         //Key information from the EncryptedKey
+         byte[] ek = encrKeyBuilder.getEphemeralKey();
+         String tokneIdentifier = encrKeyBuilder.getTokneIdentifier();         
+         
+         //Derived key encryption
+         WSSecDKSign sigBuilder = new WSSecDKSign();
+         sigBuilder.setExternalKey(ek, tokneIdentifier);
+         sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
+         Document signedDoc = sigBuilder.build(doc, crypto, secHeader);
+         
+         encrKeyBuilder.commit(signedDoc, crypto, secHeader);
+         
          Message signedMessage = (Message) SOAPUtil.toSOAPMessage(doc);
          if (log.isDebugEnabled()) {
              log.debug("Encrypted message: 3DES  + DerivedKeys");
-             XMLUtils.PrettyElementToWriter(signedMessage.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out));
+             XMLUtils.PrettyElementToWriter(signedMessage.getSOAPEnvelope()
+                    .getAsDOM(), new PrintWriter(System.out));
          }
-//         String out = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
-//         System.out.println(out);
+//         String out = org.apache.ws.security.util.XMLUtils
+//                .PrettyDocumentToString(signedDoc);
+//        System.out.println(out);
          verify(doc);
      }
      
+     public void testSignatureEncrypt() throws Exception {
+        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+        Document doc = unsignedEnvelope.getAsDocument();
+        WSSecHeader secHeader = new WSSecHeader();
+        secHeader.insertSecurityHeader(doc);
+
+        //EncryptedKey
+        WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+        encrKeyBuilder.setEncryptionUser("wss4jcert");
+        encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+        encrKeyBuilder.build(doc, crypto, secHeader);
+
+        //Key information from the EncryptedKey
+        byte[] ek = encrKeyBuilder.getEphemeralKey();
+        String tokneIdentifier = encrKeyBuilder.getTokneIdentifier();
+
+        //Derived key encryption
+        WSSecDKSign sigBuilder = new WSSecDKSign();
+        sigBuilder.setExternalKey(ek, tokneIdentifier);
+        sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
+        log.info("Before HMAC-SHA1 signature");
+        Document signedDoc = sigBuilder.build(doc, crypto, secHeader);
+
+        //Derived key signature
+        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+        encrBuilder.setExternalKey(ek, tokneIdentifier);
+        Document signedEncryptedDoc = encrBuilder.build(signedDoc, crypto,
+                secHeader);
+
+        encrKeyBuilder.commit(signedEncryptedDoc, crypto, secHeader);
+
+        Message signedMessage = (Message) SOAPUtil
+                .toSOAPMessage(signedEncryptedDoc);
+
+        if (log.isDebugEnabled()) {
+            log.debug("Encrypted message: 3DES  + DerivedKeys");
+            XMLUtils.PrettyElementToWriter(signedMessage.getSOAPEnvelope()
+                    .getAsDOM(), new PrintWriter(System.out));
+        }
+//        String out = org.apache.ws.security.util.XMLUtils
+//                .PrettyDocumentToString(signedEncryptedDoc);
+//        System.out.println(out);
+        verify(signedEncryptedDoc);
+    }
+     
+     public void testEncryptSignature() throws Exception {
+         SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
+         Document doc = unsignedEnvelope.getAsDocument();
+         WSSecHeader secHeader = new WSSecHeader();
+         secHeader.insertSecurityHeader(doc);
+
+         //EncryptedKey
+         WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
+         encrKeyBuilder.setEncryptionUser("wss4jcert");
+         encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+         encrKeyBuilder.build(doc, crypto, secHeader);
+         
+         //Key information from the EncryptedKey
+         byte[] ek = encrKeyBuilder.getEphemeralKey();
+         String tokneIdentifier = encrKeyBuilder.getTokneIdentifier();
+         
+         //Derived key encryption
+         WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
+         encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
+         encrBuilder.setExternalKey(ek, tokneIdentifier);
+         Document encryptedDoc = encrBuilder.build(doc, crypto, secHeader);
+         
+         //Derived key signature
+         WSSecDKSign sigBuilder = new WSSecDKSign();
+         sigBuilder.setExternalKey(ek, tokneIdentifier);
+         sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
+         log.info("Before HMAC-SHA1 signature");
+         Document encryptedSignedDoc = sigBuilder.build(encryptedDoc, crypto,
+                secHeader);
+         
+         encrKeyBuilder.commit(encryptedSignedDoc, crypto, secHeader);
+         
+         Message signedMessage = (Message) SOAPUtil
+                .toSOAPMessage(encryptedSignedDoc);
+         
+         if (log.isDebugEnabled()) {
+            log.debug("Encrypted message: 3DES  + DerivedKeys");
+            XMLUtils.PrettyElementToWriter(signedMessage.getSOAPEnvelope()
+                    .getAsDOM(), new PrintWriter(System.out));
+        }
+        
+//         String out = org.apache.ws.security.util.XMLUtils
+//                .PrettyDocumentToString(encryptedSignedDoc);
+//         System.out.println(out);
+         verify(encryptedSignedDoc);
+     }
     
     /**
      * Verifies the soap envelope
@@ -216,7 +356,8 @@
                  */
                 pc.setPassword("security");
             } else {
-                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
+                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