You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ws.apache.org by co...@apache.org on 2013/11/11 17:54:53 UTC

svn commit: r1540772 [1/5] - in /webservices/wss4j/trunk: parent/ ws-security-common/ ws-security-common/src/main/java/org/apache/wss4j/common/ext/ ws-security-common/src/main/java/org/apache/wss4j/common/util/ ws-security-common/src/test/java/org/apac...

Author: coheigea
Date: Mon Nov 11 16:54:52 2013
New Revision: 1540772

URL: http://svn.apache.org/r1540772
Log:
[WSS-430] - Merging a tidied up version of Marc's SwA patch

Added:
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/Attachment.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentRequestCallback.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentResultCallback.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/AttachmentUtils.java
    webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/CRLFOutputStream.java
    webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/
    webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/AttachmentTest.java
    webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/CRLFOutputStreamTest.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/resolvers/
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/resolvers/ResolverAttachment.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentCiphertextTransform.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentCompleteSignatureTransform.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentCompleteSignatureTransformProvider.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentContentSignatureTransform.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentContentSignatureTransformProvider.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/transform/AttachmentTransformParameterSpec.java
    webservices/wss4j/trunk/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/AttachmentTest.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/resourceResolvers/ResolverAttachment.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/transformer/AttachmentCompleteSignatureTransform.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/transformer/AttachmentContentSignatureTransform.java
    webservices/wss4j/trunk/ws-security-stax/src/test/java/org/apache/wss4j/stax/test/AttachmentTest.java
Modified:
    webservices/wss4j/trunk/parent/pom.xml
    webservices/wss4j/trunk/ws-security-common/pom.xml
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSConstants.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/EncryptionAction.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/SignatureAction.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/RequestData.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecBase.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecEncrypt.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureBase.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedDataProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/EncryptedKeyProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/ReferenceListProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/SignatureProcessor.java
    webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/processor/X509Util.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/ext/WSSConstants.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/ext/WSSSecurityProperties.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/ext/WSSUtils.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/DecryptInputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/input/WSSSignatureReferenceVerifyInputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/output/EncryptEndingOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/output/EncryptOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/output/SecurityHeaderOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/output/WSSSignatureEndingOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/processor/output/WSSSignatureOutputProcessor.java
    webservices/wss4j/trunk/ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/transformer/STRTransformer.java
    webservices/wss4j/trunk/ws-security-stax/src/main/resources/wss/wss-config.xml

Modified: webservices/wss4j/trunk/parent/pom.xml
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/parent/pom.xml?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/parent/pom.xml (original)
+++ webservices/wss4j/trunk/parent/pom.xml Mon Nov 11 16:54:52 2013
@@ -36,6 +36,7 @@
     <properties>
         <bcprov.version>1.49</bcprov.version>
         <ehcache.version>2.7.4</ehcache.version>
+        <geronimo.javamail.version>1.7.1</geronimo.javamail.version>
         <jasypt.version>1.9.0</jasypt.version>
         <log4j.version>1.2.17</log4j.version>
         <neethi.version>3.0.2</neethi.version>
@@ -92,6 +93,11 @@
                 <version>${opensaml.version}</version>
             </dependency>
             <dependency>
+                <groupId>org.apache.geronimo.specs</groupId>
+                <artifactId>geronimo-javamail_1.4_spec</artifactId>
+                <version>${geronimo.javamail.version}</version>
+            </dependency>
+            <dependency>
                 <groupId>log4j</groupId>
                 <artifactId>log4j</artifactId>
                 <version>${log4j.version}</version>

Modified: webservices/wss4j/trunk/ws-security-common/pom.xml
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/pom.xml?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/pom.xml (original)
+++ webservices/wss4j/trunk/ws-security-common/pom.xml Mon Nov 11 16:54:52 2013
@@ -279,6 +279,11 @@
             <scope>compile</scope>
         </dependency>
         <dependency>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-javamail_1.4_spec</artifactId>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <scope>test</scope>

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/Attachment.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/Attachment.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/Attachment.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/Attachment.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.ext;
+
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Attachment {
+
+    private String id;
+    private String mimeType;
+    private final Map<String, String> headers = new HashMap<String, String>();
+    private InputStream sourceStream;
+
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getMimeType() {
+        return mimeType;
+    }
+
+    public void setMimeType(String mimeType) {
+        this.mimeType = mimeType;
+    }
+
+    public void addHeader(String name, String value) {
+        this.headers.put(name, value);
+    }
+
+    public void addHeaders(Map<String, String> headers) {
+        this.headers.putAll(headers);
+    }
+
+    public Map<String, String> getHeaders() {
+        return headers;
+    }
+
+    public InputStream getSourceStream() {
+        return sourceStream;
+    }
+
+    public void setSourceStream(InputStream sourceStream) {
+        this.sourceStream = sourceStream;
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentRequestCallback.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentRequestCallback.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentRequestCallback.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentRequestCallback.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.ext;
+
+import javax.security.auth.callback.Callback;
+import java.util.List;
+
+public class AttachmentRequestCallback implements Callback {
+
+    private String attachmentId;
+    private List<Attachment> attachments;
+
+    /**
+     * The requested attachment which will be secured. If null all attachments are requested
+     *
+     * @return
+     */
+    public String getAttachmentId() {
+        return attachmentId;
+    }
+
+    public void setAttachmentId(String attachmentId) {
+        this.attachmentId = attachmentId;
+    }
+
+    public List<Attachment> getAttachments() {
+        return attachments;
+    }
+
+    public void setAttachments(List<Attachment> attachments) {
+        this.attachments = attachments;
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentResultCallback.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentResultCallback.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentResultCallback.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/ext/AttachmentResultCallback.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.ext;
+
+import javax.security.auth.callback.Callback;
+
+public class AttachmentResultCallback implements Callback {
+
+    private String attachmentId;
+    private Attachment attachment;
+
+    /**
+     * The requested attachment which will be secured. If null all attachments are requested
+     *
+     * @return
+     */
+    public String getAttachmentId() {
+        return attachmentId;
+    }
+
+    public void setAttachmentId(String attachmentId) {
+        this.attachmentId = attachmentId;
+    }
+
+    public Attachment getAttachment() {
+        return attachment;
+    }
+
+    public void setAttachment(Attachment attachment) {
+        this.attachment = attachment;
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/AttachmentUtils.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/AttachmentUtils.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/AttachmentUtils.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/AttachmentUtils.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,609 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.util;
+
+import org.apache.wss4j.common.ext.Attachment;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.xml.security.encryption.XMLCipher;
+import org.apache.xml.security.stax.impl.util.MultiInputStream;
+
+import javax.crypto.Cipher;
+import javax.crypto.CipherInputStream;
+import javax.crypto.spec.IvParameterSpec;
+import javax.mail.internet.MimeUtility;
+
+import java.io.*;
+import java.net.URLDecoder;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.util.*;
+
+public class AttachmentUtils {
+
+    public static final String MIME_HEADER_CONTENT_DESCRIPTION = "Content-Description";
+    public static final String MIME_HEADER_CONTENT_DISPOSITION = "Content-Disposition";
+    public static final String MIME_HEADER_CONTENT_ID = "Content-ID";
+    public static final String MIME_HEADER_CONTENT_LOCATION = "Content-Location";
+    public static final String MIME_HEADER_CONTENT_TYPE = "Content-Type";
+
+    public static final char DOUBLE_QUOTE = '"';
+    public static final char SINGLE_QUOTE = '\'';
+    public static final char LEFT_PARENTHESIS = '(';
+    public static final char RIGHT_PARENTHESIS = ')';
+    public static final char CARRIAGE_RETURN = '\r';
+    public static final char LINEFEED = '\n';
+    public static final char SPACE = ' ';
+    public static final char HTAB = '\t';
+    public static final char EQUAL = '=';
+    public static final char ASTERISK = '*';
+    public static final char SEMICOLON = ';';
+    public static final char BACKSLASH = '\\';
+
+    public static final String PARAM_CHARSET = "charset";
+    public static final String PARAM_CREATION_DATE = "creation-date";
+    public static final String PARAM_FILENAME = "filename";
+    public static final String PARAM_MODIFICATION_DATE = "modification-date";
+    public static final String PARAM_PADDING = "padding";
+    public static final String PARAM_READ_DATE = "read-date";
+    public static final String PARAM_SIZE = "size";
+    public static final String PARAM_TYPE = "type";
+
+    public static final Set<String> ALL_PARAMS = new HashSet<String>();
+
+    static {
+        ALL_PARAMS.add(PARAM_CHARSET);
+        ALL_PARAMS.add(PARAM_CREATION_DATE);
+        ALL_PARAMS.add(PARAM_FILENAME);
+        ALL_PARAMS.add(PARAM_MODIFICATION_DATE);
+        ALL_PARAMS.add(PARAM_PADDING);
+        ALL_PARAMS.add(PARAM_READ_DATE);
+        ALL_PARAMS.add(PARAM_SIZE);
+        ALL_PARAMS.add(PARAM_TYPE);
+    }
+
+
+    public static void canonizeMimeHeaders(OutputStream os, Map<String, String> headers) throws IOException {
+        //5.4.1 MIME header canonicalization:
+
+        //3. sorting
+        Map<String, String> sortedHeaders = new TreeMap<String, String>();
+        Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
+        while (iterator.hasNext()) {
+            Map.Entry<String, String> next = iterator.next();
+            String name = next.getKey();
+            String value = next.getValue();
+
+            //2. only listed headers; 4. case
+            if (MIME_HEADER_CONTENT_DESCRIPTION.equalsIgnoreCase(name)) {
+                sortedHeaders.put(MIME_HEADER_CONTENT_DESCRIPTION,
+                        //9. uncomment
+                        uncomment(
+                                //6. decode
+                                MimeUtility.decodeText(
+                                        //5. unfold
+                                        MimeUtility.unfold(value)
+                                )
+                        )
+                );
+            } else if (MIME_HEADER_CONTENT_DISPOSITION.equalsIgnoreCase(name)) {
+                sortedHeaders.put(MIME_HEADER_CONTENT_DISPOSITION,
+                        decodeRfc2184(
+                                //9. uncomment
+                                uncomment(
+                                        //8. unfold ws
+                                        unfoldWhitespace(
+                                                //5. unfold
+                                                MimeUtility.unfold(value)
+                                        )
+                                )
+                        )
+                );
+            } else if (MIME_HEADER_CONTENT_ID.equalsIgnoreCase(name)) {
+                sortedHeaders.put(MIME_HEADER_CONTENT_ID,
+                        //9. uncomment
+                        uncomment(
+                                //8. unfold ws
+                                unfoldWhitespace(
+                                        //5. unfold
+                                        MimeUtility.unfold(value)
+                                )
+                        )
+                );
+            } else if (MIME_HEADER_CONTENT_LOCATION.equalsIgnoreCase(name)) {
+                sortedHeaders.put(MIME_HEADER_CONTENT_LOCATION,
+                        //9. uncomment
+                        uncomment(
+                                //8. unfold ws
+                                unfoldWhitespace(
+                                        //5. unfold
+                                        MimeUtility.unfold(value)
+                                )
+                        )
+                );
+            } else if (MIME_HEADER_CONTENT_TYPE.equalsIgnoreCase(name)) {
+                sortedHeaders.put(MIME_HEADER_CONTENT_TYPE,
+                        decodeRfc2184(
+                                //9. uncomment
+                                uncomment(
+                                        //8. unfold ws
+                                        unfoldWhitespace(
+                                                //5. unfold
+                                                MimeUtility.unfold(value)
+                                        )
+                                )
+                        )
+                );
+            }
+        }
+        //2. default content-type
+        if (!sortedHeaders.containsKey(MIME_HEADER_CONTENT_TYPE)) {
+            sortedHeaders.put(MIME_HEADER_CONTENT_TYPE, "text/plain;charset=\"us-ascii\"");
+        }
+
+        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8");
+
+        Iterator<Map.Entry<String, String>> entryIterator = sortedHeaders.entrySet().iterator();
+        while (entryIterator.hasNext()) {
+            Map.Entry<String, String> next = entryIterator.next();
+            String name = next.getKey();
+            String value = next.getValue();
+
+            //12.
+            outputStreamWriter.write(name);
+            outputStreamWriter.write(':');
+            outputStreamWriter.write(value);
+            //18. CRLF pair
+            if (!value.endsWith("\r\n")) {
+                outputStreamWriter.write("\r\n");
+            }
+        }
+        outputStreamWriter.flush();
+    }
+
+    public static String unfoldWhitespace(String text) {
+        int count = 0;
+        char[] chars = text.toCharArray();
+        for (int i = 0; i < chars.length; i++) {
+            if (SPACE != chars[i] &&
+                    HTAB != chars[i]) {
+                break;
+            }
+            count++;
+        }
+        return text.substring(count, chars.length);
+    }
+
+    //removes any CRLF followed by a whitespace
+    public static String unfold(String text) {
+
+        if (text.length() < 3) {
+            return text;
+        }
+
+        StringBuilder stringBuilder = new StringBuilder();
+
+        for (int i = 0; i < text.length() - 2; i++) {
+            char ch1 = text.charAt(i);
+            final char ch2 = text.charAt(i + 1);
+            final char ch3 = text.charAt(i + 2);
+
+            if (CARRIAGE_RETURN == ch1 &&
+                    LINEFEED == ch2 &&
+                    (SPACE == ch3 ||
+                            HTAB == ch3)) {
+
+                i += 2;
+                if (i >= text.length() - 3) {
+                    for (i++; i < text.length(); i++) { //NOPMD
+                        stringBuilder.append(text.charAt(i));
+                    }
+                }
+                continue;
+            }
+            stringBuilder.append(ch1);
+            if (i == text.length() - 3) {
+                stringBuilder.append(ch2);
+                stringBuilder.append(ch3);
+            }
+        }
+        return stringBuilder.toString();
+    }
+
+    public static String decodeRfc2184(String text) throws UnsupportedEncodingException {
+        if (!text.contains(";")) {
+            return text;
+        }
+
+        String[] params = text.split(";");
+        //first part is the Mime-Header-Value
+        StringBuilder stringBuilder = new StringBuilder();
+        //10. lower case
+        stringBuilder.append(params[0].toLowerCase());
+
+        TreeMap<String, String> paramMap = new TreeMap<String, String>();
+
+        String parameterName = null;
+        String parameterValue = null;
+        String charset = "us-ascii";
+        for (int i = 1; i < params.length; i++) {
+            String param = params[i];
+
+            int index = param.indexOf(EQUAL);
+            String pName = param.substring(0, index).trim().toLowerCase();
+            String pValue = param.substring(index + 1).trim();
+
+            int idx = pName.lastIndexOf(ASTERISK);
+            if (idx == pName.length() - 1) {
+                //language encoded
+                pName = pName.substring(0, pName.length() - 1);
+
+                int charsetIdx = pValue.indexOf(SINGLE_QUOTE);
+                if (charsetIdx >= 0) {
+                    charset = pValue.substring(0, charsetIdx);
+                }
+                pValue = pValue.substring(pValue.lastIndexOf(SINGLE_QUOTE) + 1);
+                pValue = URLDecoder.decode(pValue, MimeUtility.javaCharset(charset));
+            }
+            idx = pName.lastIndexOf(ASTERISK);
+            if (idx >= 0) {
+                //continuation
+                //int curr = Integer.parseInt(pName.substring(idx+1).trim());
+                String pn = pName.substring(0, idx).trim();
+                if (pn.equals(parameterName)) {
+                    parameterValue = concatParamValues(parameterValue, pValue);
+                } else if (parameterName == null) {
+                    parameterName = pn;
+                    parameterValue = pValue;
+                } else {
+                    if (ALL_PARAMS.contains(parameterName)) {
+                        parameterValue = parameterValue.toLowerCase();
+                    }
+                    paramMap.put(parameterName,
+                            unquoteInnerText(
+                                    quote(parameterValue)
+                            )
+                    );
+                }
+            } else {
+                if (parameterName != null) {
+                    if (ALL_PARAMS.contains(parameterName)) {
+                        parameterValue = parameterValue.toLowerCase();
+                    }
+                    paramMap.put(parameterName,
+                            unquoteInnerText(
+                                    quote(parameterValue)
+                            )
+                    );
+                    parameterName = null;
+                    parameterValue = null;
+                }
+
+                if (ALL_PARAMS.contains(pName)) {
+                    pValue = pValue.toLowerCase();
+                }
+                paramMap.put(pName,
+                        unquoteInnerText(
+                                quote(pValue)
+                        )
+                );
+            }
+        }
+        if (parameterName != null) {
+            if (ALL_PARAMS.contains(parameterName)) {
+                parameterValue = parameterValue.toLowerCase();
+            }
+            paramMap.put(parameterName,
+                    unquoteInnerText(
+                            quote(parameterValue)
+                    )
+            );
+        }
+
+        Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
+        while (iterator.hasNext()) {
+            Map.Entry<String, String> next = iterator.next();
+            stringBuilder.append(SEMICOLON);
+            stringBuilder.append(next.getKey());
+            stringBuilder.append(EQUAL);
+            stringBuilder.append(next.getValue());
+        }
+        return stringBuilder.toString();
+    }
+
+    public static String concatParamValues(String a, String b) {
+        if (DOUBLE_QUOTE == a.charAt(a.length() - 1)) {
+            a = a.substring(0, a.length() - 1);
+        }
+        if (DOUBLE_QUOTE == b.charAt(0)) {
+            b = b.substring(1);
+        }
+        return a + b;
+    }
+
+    public static String quote(String text) {
+        char startChar = text.charAt(0);
+        char endChar = text.charAt(text.length() - 1);
+        if (DOUBLE_QUOTE == startChar &&
+                DOUBLE_QUOTE == endChar) {
+            return text;
+        } else if (DOUBLE_QUOTE != startChar &&
+                DOUBLE_QUOTE != endChar) {
+            return DOUBLE_QUOTE + text + DOUBLE_QUOTE;
+        } else if (DOUBLE_QUOTE != startChar) {
+            return DOUBLE_QUOTE + text;
+        } else {
+            return text + DOUBLE_QUOTE;
+        }
+    }
+
+    public static String unquoteInnerText(String text) {
+        StringBuilder stringBuilder = new StringBuilder();
+        for (int i = 0; i < text.length() - 1; i++) {
+            char c = text.charAt(i);
+            char c1 = text.charAt(i + 1);
+            if (i == 0 && DOUBLE_QUOTE == c) {
+                stringBuilder.append(c);
+                continue;
+            }
+            if (BACKSLASH == c && (DOUBLE_QUOTE == c1 || BACKSLASH == c1)) {
+                if (i != 0 && i != text.length() - 2) {
+                    stringBuilder.append(c);
+                }
+                stringBuilder.append(c1);
+                i++;
+            } else if (DOUBLE_QUOTE == c) {
+                stringBuilder.append(BACKSLASH);
+                stringBuilder.append(c);
+            } else if (BACKSLASH == c) {
+                stringBuilder.append(c1);
+                i++;
+            } else {
+                stringBuilder.append(c);
+                if (i == text.length() - 2 && DOUBLE_QUOTE == c1) {
+                    stringBuilder.append(c1);
+                }
+            }
+        }
+        return stringBuilder.toString();
+    }
+
+    /*
+         * Removes any comment outside quoted text. Comments are enclosed between ()
+         */
+    public static String uncomment(String text) {
+        StringBuilder stringBuilder = new StringBuilder();
+
+        int inComment = 0;
+        outer:
+        for (int i = 0; i < text.length(); i++) {
+            char ch = text.charAt(i);
+
+            if (DOUBLE_QUOTE == ch) {
+                stringBuilder.append(ch);
+                for (i++; i < text.length(); i++) { //NOPMD
+                    ch = text.charAt(i);
+                    stringBuilder.append(ch);
+                    if (DOUBLE_QUOTE == ch) {
+                        continue outer;
+                    }
+                }
+            }
+            if (LEFT_PARENTHESIS == ch) {
+                inComment++;
+                for (i++; i < text.length(); i++) { //NOPMD
+                    ch = text.charAt(i);
+                    if (LEFT_PARENTHESIS == ch) {
+                        inComment++;
+                    }
+                    if (RIGHT_PARENTHESIS == ch) {
+                        inComment--;
+                        if (inComment == 0) {
+                            continue outer;
+                        }
+                    }
+                }
+            }
+            stringBuilder.append(ch);
+        }
+        return stringBuilder.toString();
+    }
+
+    public static void readAndReplaceEncryptedAttachmentHeaders(
+            Map<String, String> headers, InputStream attachmentInputStream) throws IOException, WSSecurityException {
+
+        //read and replace headers
+        List<String> headerLines = new ArrayList<String>();
+        StringBuilder stringBuilder = new StringBuilder();
+        boolean cr = false;
+        int ch;
+        int lineLength = 0;
+        while ((ch = attachmentInputStream.read()) != -1) {
+            if (ch == '\r') {
+                cr = true;
+            } else if (ch == '\n' && cr) {
+                cr = false;
+                if (lineLength == 1 && stringBuilder.charAt(0) == '\r') {
+                    break;
+                }
+                if (headerLines.size() > 100) {
+                    //so much headers? go away....
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILED_CHECK);
+                }
+                headerLines.add(stringBuilder.substring(0, stringBuilder.length() - 1));
+                lineLength = 0;
+                stringBuilder.delete(0, stringBuilder.length());
+                continue;
+            }
+            lineLength++;
+            //Lines in a message MUST be a maximum of 998 characters excluding the CRLF
+            if (lineLength >= 1000) {
+                throw new WSSecurityException(
+                        WSSecurityException.ErrorCode.FAILED_CHECK);
+            }
+            stringBuilder.append((char) ch);
+        }
+
+        for (int i = 0; i < headerLines.size(); i++) {
+            String s = headerLines.get(i);
+            int idx = s.indexOf(':');
+            if (idx == -1) {
+                throw new WSSecurityException(
+                        WSSecurityException.ErrorCode.FAILED_CHECK);
+            }
+            headers.put(s.substring(0, idx), s.substring(idx + 1));
+        }
+    }
+
+    public static InputStream setupAttachmentDecryptionStream(
+            final String encAlgo, final Cipher cipher, final Key key, InputStream inputStream)
+            throws WSSecurityException {
+
+        CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher) {
+
+            private boolean firstRead = true;
+
+            private void initCipher() throws IOException {
+                // For now, we only work with Block ciphers, so this will work.
+                // This should probably be put into the JCE mapper.
+                int ivLen = cipher.getBlockSize();
+                if (XMLCipher.AES_128_GCM.equals(encAlgo) || XMLCipher.AES_192_GCM.equals(encAlgo) || XMLCipher.AES_256_GCM.equals(encAlgo)) {
+                    ivLen = 12;
+                }
+
+                byte[] ivBytes = new byte[ivLen];
+                int read = 0;
+                while ((read += super.in.read(ivBytes, read, ivLen - read)) != ivLen) ; //NOPMD
+                IvParameterSpec iv = new IvParameterSpec(ivBytes);
+
+                try {
+                    cipher.init(Cipher.DECRYPT_MODE, key, iv);
+                } catch (InvalidKeyException e) {
+                    throw new IOException(e);
+                } catch (InvalidAlgorithmParameterException e) {
+                    throw new IOException(e);
+                }
+            }
+
+            @Override
+            public int read() throws IOException {
+                if (firstRead) {
+                    initCipher();
+                    firstRead = false;
+                }
+                return super.read();
+            }
+
+            @Override
+            public int read(byte[] bytes) throws IOException {
+                if (firstRead) {
+                    initCipher();
+                    firstRead = false;
+                }
+                return super.read(bytes);
+            }
+
+            @Override
+            public int read(byte[] bytes, int i, int i2) throws IOException {
+                if (firstRead) {
+                    initCipher();
+                    firstRead = false;
+                }
+                return super.read(bytes, i, i2);
+            }
+
+            @Override
+            public long skip(long l) throws IOException {
+                if (firstRead) {
+                    initCipher();
+                    firstRead = false;
+                }
+                return super.skip(l);
+            }
+
+            @Override
+            public int available() throws IOException {
+                if (firstRead) {
+                    initCipher();
+                    firstRead = false;
+                }
+                return super.available();
+            }
+        };
+
+        return cipherInputStream;
+    }
+
+    public static InputStream setupAttachmentEncryptionStream(
+            Cipher cipher, boolean complete, Attachment attachment,
+            Map<String, String> headers) throws WSSecurityException {
+
+        final InputStream attachmentInputStream;
+
+        if (complete) {
+            try {
+                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "US-ASCII");
+
+                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
+                while (iterator.hasNext()) {
+                    Map.Entry<String, String> next = iterator.next();
+                    String key = next.getKey();
+                    String value = next.getValue();
+                    //5.5.2 Encryption Processing Rules
+                    //When encryption includes MIME headers, only the headers listed in this specification
+                    //for the Attachment-Complete-Signature-Transform (Section 5.3.2) are to be included in
+                    //the encryption. If a header listed in the profile is present it MUST be included in
+                    //the encryption. If a header is not listed in this profile, then it MUST NOT be
+                    //included in the encryption.
+                    if (AttachmentUtils.MIME_HEADER_CONTENT_DESCRIPTION.equals(key) ||
+                            AttachmentUtils.MIME_HEADER_CONTENT_DISPOSITION.equals(key) ||
+                            AttachmentUtils.MIME_HEADER_CONTENT_ID.equals(key) ||
+                            AttachmentUtils.MIME_HEADER_CONTENT_LOCATION.equals(key) ||
+                            AttachmentUtils.MIME_HEADER_CONTENT_TYPE.equals(key)
+                            ) {
+                        iterator.remove();
+                        outputStreamWriter.write(key);
+                        outputStreamWriter.write(':');
+                        outputStreamWriter.write(value);
+                        outputStreamWriter.write("\r\n");
+                    }
+                }
+                outputStreamWriter.write("\r\n");
+                outputStreamWriter.close();
+                attachmentInputStream = new MultiInputStream(
+                        new ByteArrayInputStream(byteArrayOutputStream.toByteArray()),
+                        attachment.getSourceStream()
+                );
+            } catch (UnsupportedEncodingException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, e);
+            } catch (IOException e) {
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, e);
+            }
+        } else {
+            attachmentInputStream = attachment.getSourceStream();
+        }
+
+        final ByteArrayInputStream ivInputStream = new ByteArrayInputStream(cipher.getIV());
+        final CipherInputStream cipherInputStream = new CipherInputStream(attachmentInputStream, cipher);
+
+        return new MultiInputStream(ivInputStream, cipherInputStream);
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/CRLFOutputStream.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/CRLFOutputStream.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/CRLFOutputStream.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/main/java/org/apache/wss4j/common/util/CRLFOutputStream.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,82 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.util;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class CRLFOutputStream extends FilterOutputStream {
+
+    private static final byte CR = '\r';
+    private static final byte LF = '\n';
+    private static final byte[] CRLF = new byte[]{CR, LF};
+
+    private boolean lastByteCR = false;
+
+    public CRLFOutputStream(OutputStream out) {
+        super(out);
+    }
+
+    @Override
+    public void write(int b) throws IOException {
+        if (b == CR) {
+            out.write(CRLF);
+            lastByteCR = true;
+        } else if (b == LF) {
+            if (lastByteCR) {
+                lastByteCR = false;
+            } else {
+                out.write(CRLF);
+            }
+        } else {
+            out.write(b);
+            lastByteCR = false;
+        }
+    }
+
+    @Override
+    public void write(byte[] b, int off, int len) throws IOException {
+
+        int start = off;
+        for (int i = off; i < len; i++) {
+            if (b[i] == CR) {
+                out.write(b, start, i + 1 - start);
+                out.write(LF);
+                lastByteCR = true;
+                start = i + 1;
+            } else if (b[i] == LF) {
+                if (lastByteCR) {
+                    lastByteCR = false;
+                    start++;
+                } else {
+                    int l = i - start;
+                    if (l > 0) {
+                        out.write(b, start, l);
+                    }
+                    out.write(CRLF);
+                    start = i + 1;
+                }
+            } else {
+                lastByteCR = false;
+            }
+        }
+        out.write(b, start, len - start);
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/AttachmentTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/AttachmentTest.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/AttachmentTest.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/AttachmentTest.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,217 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.attachment;
+
+import org.junit.Assert;
+import org.apache.wss4j.common.util.AttachmentUtils;
+
+public class AttachmentTest {
+
+    @org.junit.Test
+    public void testMimeHeaderUncomment_1() throws Exception {
+        Assert.assertEquals(
+                "\"a\" \"(b)\" c  test",
+                AttachmentUtils.uncomment("\"a\" \"(b)\" c ((\"d\")) test"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUncomment_2() throws Exception {
+        Assert.assertEquals(
+                "",
+                AttachmentUtils.uncomment("(\"a\" \"(b)\" c ((\"d\")) test)"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUncomment_3() throws Exception {
+        Assert.assertEquals(
+                "\"a\" \"(\"b\")\" test",
+                AttachmentUtils.uncomment("\"a\" \"(\"b\")\" (c(\"d\"))test"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_1() throws Exception {
+        Assert.assertEquals(
+                "\r\n",
+                AttachmentUtils.unfold("\r\n"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_2() throws Exception {
+        Assert.assertEquals(
+                "\r\na",
+                AttachmentUtils.unfold("\r\na"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_3() throws Exception {
+        Assert.assertEquals(
+                "",
+                AttachmentUtils.unfold("\r\n "));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_4() throws Exception {
+        Assert.assertEquals(
+                "",
+                AttachmentUtils.unfold("\r\n\t"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_5() throws Exception {
+        Assert.assertEquals(
+                "aa",
+                AttachmentUtils.unfold("a\r\n\ta"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_6() throws Exception {
+        Assert.assertEquals(
+                "aaa",
+                AttachmentUtils.unfold("a\r\n\taa"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_7() throws Exception {
+        Assert.assertEquals(
+                "aaaa",
+                AttachmentUtils.unfold("\r\n\taaaa"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_8() throws Exception {
+        Assert.assertEquals(
+                "a",
+                AttachmentUtils.unfold("\r\n\ta\r\n "));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_9() throws Exception {
+        Assert.assertEquals(
+                "\r\n\ra",
+                AttachmentUtils.unfold("\r\n\ra\r\n "));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfold_10() throws Exception {
+        Assert.assertEquals(
+                "\r\n",
+                AttachmentUtils.unfold("\r\n \r\n \r\n"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfoldWS_1() throws Exception {
+        Assert.assertEquals(
+                "a ",
+                AttachmentUtils.unfoldWhitespace(" a "));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfoldWS_2() throws Exception {
+        Assert.assertEquals(
+                "",
+                AttachmentUtils.unfoldWhitespace(""));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfoldWS_3() throws Exception {
+        Assert.assertEquals(
+                "",
+                AttachmentUtils.unfoldWhitespace(" \t \t\t  "));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnfoldWS_4() throws Exception {
+        Assert.assertEquals(
+                "a\ta\t  a",
+                AttachmentUtils.unfoldWhitespace(" \t a\ta\t  a"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderDecodeRfc2184_1() throws Exception {
+        Assert.assertEquals(
+                "message/external-body;access-type=\"URL\";" +
+                        "test=\"true\";" +
+                        "url=\"ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\""
+                ,
+                AttachmentUtils.decodeRfc2184(
+                        "Message/External-Body; access-type=URL;" +
+                                "URL*0=\"ftp://\";" +
+                                "URL*1=\"cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\";" +
+                                "test=true"));
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderDecodeRfc2184_2() throws Exception {
+        Assert.assertEquals(
+                "message/external-body;access-type=\"URL\";" +
+                        "url=\"ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\"",
+                AttachmentUtils.decodeRfc2184(
+                        "Message/External-Body; access-type=URL;" +
+                                "URL*0=\"ftp://\";" +
+                                "URL*1=\"cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\""
+                )
+        );
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderDecodeRfc2184_3() throws Exception {
+        Assert.assertEquals(
+                "application/x-stuff;" +
+                        "title=\"This is ***fun***\"",
+                AttachmentUtils.decodeRfc2184(
+                        "application/x-stuff;" +
+                                "title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A"
+                )
+        );
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderDecodeRfc2184_4() throws Exception {
+        Assert.assertEquals(
+                "application/x-stuff;" +
+                        "title=\"This is even more ***fun*** isn't it!\"",
+                AttachmentUtils.decodeRfc2184(
+                        "application/x-stuff;" +
+                                "title*1*=us-ascii'en'This%20is%20even%20more%20;" +
+                                "title*2*=%2A%2A%2Afun%2A%2A%2A%20;" +
+                                "title*3=\"isn't it!\""
+                )
+        );
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnquoteInnerText_1() throws Exception {
+        Assert.assertEquals(
+                "\"\\\"\\\"\\\\A\"",
+                AttachmentUtils.unquoteInnerText(
+                        "\\\"\"\"\\\\\\A\\\""
+                )
+        );
+    }
+
+    @org.junit.Test
+    public void testMimeHeaderUnquoteInnerText_2() throws Exception {
+        Assert.assertEquals(
+                "\"a\"",
+                AttachmentUtils.unquoteInnerText(
+                        "\\\"a\\\""
+                )
+        );
+    }
+}

Added: webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/CRLFOutputStreamTest.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/CRLFOutputStreamTest.java?rev=1540772&view=auto
==============================================================================
--- webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/CRLFOutputStreamTest.java (added)
+++ webservices/wss4j/trunk/ws-security-common/src/test/java/org/apache/wss4j/common/attachment/CRLFOutputStreamTest.java Mon Nov 11 16:54:52 2013
@@ -0,0 +1,127 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.wss4j.common.attachment;
+
+import org.apache.wss4j.common.util.CRLFOutputStream;
+import org.junit.Assert;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Random;
+
+public class CRLFOutputStreamTest {
+
+    @org.junit.Test
+    public void testBytePerByte() throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        CRLFOutputStream crlfOutputStream = new CRLFOutputStream(baos);
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('a');
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('\r');
+        crlfOutputStream.write('\n');
+        crlfOutputStream.write('a');
+        crlfOutputStream.write('a');
+        crlfOutputStream.write('a');
+        crlfOutputStream.close();
+        Assert.assertArrayEquals("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\na\r\n\r\naaa".getBytes(), baos.toByteArray());
+    }
+
+    @org.junit.Test
+    public void testBytes() throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        CRLFOutputStream crlfOutputStream = new CRLFOutputStream(baos);
+        crlfOutputStream.write("\n\r\r\n\n\n\r\r\ra\n\r\naaa".getBytes());
+        crlfOutputStream.close();
+        Assert.assertArrayEquals("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\na\r\n\r\naaa".getBytes(), baos.toByteArray());
+    }
+
+    @org.junit.Test
+    public void testBytes1() throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        CRLFOutputStream crlfOutputStream = new CRLFOutputStream(baos);
+        crlfOutputStream.write("aaaaaaaaaa".getBytes());
+        crlfOutputStream.close();
+        Assert.assertArrayEquals("aaaaaaaaaa".getBytes(), baos.toByteArray());
+    }
+
+    @org.junit.Test
+    public void testRandom() throws Exception {
+        byte[] pool = new byte[] {'\r', '\n', 'a'};
+        Random random = new Random();
+
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        CRLFOutputStream crlfOutputStream = new CRLFOutputStream(baos);
+
+        ByteArrayOutputStream testString = new ByteArrayOutputStream();
+
+        for (int h = 0; h < 10000; h++) {
+            if (random.nextBoolean()) {
+                byte b = pool[random.nextInt(pool.length)];
+                testString.write(b);
+                crlfOutputStream.write(b);
+            } else {
+                int byteCount = random.nextInt(1000);
+                byte[] bytes = new byte[byteCount];
+                for (int i = 0; i < byteCount; i++) {
+                     bytes[i] = pool[random.nextInt(pool.length)];
+                }
+                testString.write(bytes);
+                crlfOutputStream.write(bytes);
+            }
+        }
+
+        crlfOutputStream.close();
+        byte[] res = baos.toByteArray();
+        for (int i = 0; i < res.length; i++) {
+            byte re = res[i];
+            if (re == '\r') {
+                if (res[i + 1] != '\n') {
+                    throw new Exception("Missing \\n in\n" + createEscapedString(res) + "\n input string: " + createEscapedString(testString.toByteArray()));
+                }
+            } else if (re == '\n') {
+                if (res[i - 1] != '\r') {
+                    throw new Exception("Missing \\r in\n" + createEscapedString(res) + "\n input string: " + createEscapedString(testString.toByteArray()));
+                }
+            }
+        }
+    }
+
+    private String createEscapedString(byte[] bytes) {
+        StringBuilder stringBuilder = new StringBuilder();
+        for (int i = 0; i < bytes.length; i++) {
+            byte aByte = bytes[i];
+            if (aByte == '\r') {
+                stringBuilder.append("\\r");
+            } else if (aByte == '\n') {
+                stringBuilder.append("\\n");
+            } else {
+                stringBuilder.append((char)aByte);
+            }
+        }
+        return stringBuilder.toString();
+    }
+}

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSConstants.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSConstants.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSConstants.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSConstants.java Mon Nov 11 16:54:52 2013
@@ -96,6 +96,12 @@ public final class WSConstants {
         "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform";
     public static final String SWA_ATTACHMENT_COMPLETE_SIG_TRANS = 
         "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Complete-Signature-Transform";
+    public static final String SWA_ATTACHMENT_CIPHERTEXT_TRANS =
+        "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Ciphertext-Transform";
+    public static final String SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_CONTENT_ONLY =
+        "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only";
+    public static final String SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE =
+        "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Complete";
     
     public static final String KEYTRANSPORT_RSA15 = 
         "http://www.w3.org/2001/04/xmlenc#rsa-1_5";

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/WSSConfig.java Mon Nov 11 16:54:52 2013
@@ -35,8 +35,14 @@ import org.apache.wss4j.common.ext.WSSec
 import org.apache.wss4j.common.util.WSCurrentTimeSource;
 import org.apache.wss4j.common.util.WSTimeSource;
 import org.apache.wss4j.dom.processor.Processor;
+import org.apache.wss4j.dom.resolvers.ResolverAttachment;
+import org.apache.wss4j.dom.transform.AttachmentCiphertextTransform;
+import org.apache.wss4j.dom.transform.AttachmentCompleteSignatureTransformProvider;
+import org.apache.wss4j.dom.transform.AttachmentContentSignatureTransformProvider;
 import org.apache.wss4j.dom.validate.Validator;
 import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.transforms.Transform;
+import org.apache.xml.security.utils.resolver.ResourceResolver;
 
 /**
  * WSSConfig <p/> Carries configuration data so the WSS4J spec compliance can be
@@ -374,9 +380,32 @@ public class WSSConfig {
                     new org.apache.wss4j.dom.transform.STRTransformProvider()
                 );
 
+                Security.removeProvider("AttachmentContentSignatureTransform");
+                WSProviderConfig.appendJceProvider(
+                        "AttachmentContentSignatureTransform",
+                        new AttachmentContentSignatureTransformProvider()
+                );
+
+                Security.removeProvider("AttachmentCompleteSignatureTransform");
+                WSProviderConfig.appendJceProvider(
+                        "AttachmentCompleteSignatureTransform",
+                        new AttachmentCompleteSignatureTransformProvider()
+                );
+
                 return true;
             }
         });
+
+        try {
+            Transform.register(WSConstants.SWA_ATTACHMENT_CIPHERTEXT_TRANS,
+                    AttachmentCiphertextTransform.class);
+        } catch (Exception e) {
+            if (LOG.isDebugEnabled()) {
+                LOG.debug(e.getMessage(), e);
+            }
+        }
+
+        ResourceResolver.register(new ResolverAttachment(), false);
     }
     
     private WSSConfig() {

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/EncryptionAction.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/EncryptionAction.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/EncryptionAction.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/EncryptionAction.java Mon Nov 11 16:54:52 2013
@@ -104,6 +104,8 @@ public class EncryptionAction implements
             wsEncrypt.setCustomReferenceValue(encryptionToken.getTokenType());
         }
         
+        wsEncrypt.setAttachmentCallbackHandler(reqData.getAttachmentCallbackHandler());
+        
         try {
             wsEncrypt.build(doc, encryptionToken.getCrypto(), reqData.getSecHeader());
         } catch (WSSecurityException e) {

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/SignatureAction.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/SignatureAction.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/SignatureAction.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/action/SignatureAction.java Mon Nov 11 16:54:52 2013
@@ -92,6 +92,8 @@ public class SignatureAction implements 
             wsSign.setEncrKeySha1value(signatureToken.getSha1Value());
         }
 
+        wsSign.setAttachmentCallbackHandler(reqData.getAttachmentCallbackHandler());
+
         try {
             wsSign.prepare(doc, signatureToken.getCrypto(), reqData.getSecHeader());
 

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/RequestData.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/RequestData.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/RequestData.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/RequestData.java Mon Nov 11 16:54:52 2013
@@ -70,6 +70,7 @@ public class RequestData {
     private int derivedKeyIterations = UsernameToken.DEFAULT_ITERATION;
     private boolean useDerivedKeyForMAC = true;
     private CallbackHandler callback;
+    private CallbackHandler attachmentCallbackHandler;
     private boolean enableRevocation;
     protected boolean requireSignedEncryptedDataElements;
     private ReplayCache timestampReplayCache;
@@ -102,6 +103,7 @@ public class RequestData {
         derivedKeyIterations = UsernameToken.DEFAULT_ITERATION;
         useDerivedKeyForMAC = true;
         callback = null;
+        attachmentCallbackHandler = null;
         enableRevocation = false;
         timestampReplayCache = null;
         nonceReplayCache = null;
@@ -321,6 +323,14 @@ public class RequestData {
         return callback;
     }
 
+    public CallbackHandler getAttachmentCallbackHandler() {
+        return attachmentCallbackHandler;
+    }
+
+    public void setAttachmentCallbackHandler(CallbackHandler attachmentCallbackHandler) {
+        this.attachmentCallbackHandler = attachmentCallbackHandler;
+    }
+
     /**
      * Get the Validator instance corresponding to the QName
      * @param qName the QName with which to find a Validator instance

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/handler/WSHandler.java Mon Nov 11 16:54:52 2013
@@ -1234,6 +1234,10 @@ public abstract class WSHandler {
                     new WSEncryptionPart(partDef[0].trim(),
                             reqData.getSoapConstants().getEnvelopeURI(),
                             "Content");
+            } else if (partDef.length == 2) {
+                String mode = partDef[0].trim().substring(1);
+                String element = partDef[1].trim();
+                encPart = new WSEncryptionPart(element, mode);
             } else if (partDef.length == 3) {
                 String mode = partDef[0].trim();
                 if (mode.length() <= 1) {

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecBase.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecBase.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecBase.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecBase.java Mon Nov 11 16:54:52 2013
@@ -26,6 +26,7 @@ import org.apache.wss4j.dom.util.WSSecur
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
+import javax.security.auth.callback.CallbackHandler;
 import java.util.List;
 
 /**
@@ -47,6 +48,8 @@ public class WSSecBase {
     protected CallbackLookup callbackLookup;
 
     private WSSConfig wssConfig;
+
+    protected CallbackHandler attachmentCallbackHandler;
     
     public WSSecBase() {
     }
@@ -120,7 +123,10 @@ public class WSSecBase {
         }
         return wssConfig;
     }
-     
+
+    public void setAttachmentCallbackHandler(CallbackHandler attachmentCallbackHandler) {
+        this.attachmentCallbackHandler = attachmentCallbackHandler;
+    }
 
     /**
      * Looks up or adds a body id. <p/> First try to locate the

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecEncrypt.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecEncrypt.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecEncrypt.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecEncrypt.java Mon Nov 11 16:54:52 2013
@@ -19,6 +19,10 @@
 
 package org.apache.wss4j.dom.message;
 
+import org.apache.wss4j.common.ext.Attachment;
+import org.apache.wss4j.common.ext.AttachmentRequestCallback;
+import org.apache.wss4j.common.ext.AttachmentResultCallback;
+import org.apache.wss4j.common.util.AttachmentUtils;
 import org.apache.wss4j.dom.WSConstants;
 import org.apache.wss4j.dom.WSSConfig;
 import org.apache.wss4j.common.WSEncryptionPart;
@@ -30,9 +34,8 @@ import org.apache.wss4j.dom.message.toke
 import org.apache.wss4j.dom.message.token.Reference;
 import org.apache.wss4j.dom.message.token.SecurityTokenReference;
 import org.apache.wss4j.dom.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.algorithms.JCEMapper;
+import org.apache.xml.security.encryption.*;
 import org.apache.xml.security.keys.KeyInfo;
 import org.apache.xml.security.utils.Base64;
 import org.w3c.dom.Attr;
@@ -41,13 +44,17 @@ import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
 
+import javax.crypto.Cipher;
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
+import javax.crypto.spec.IvParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
 
+import java.security.SecureRandom;
 import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
+import java.util.*;
 
 /**
  * Encrypts a parts of a message according to WS Specification, X509 profile,
@@ -79,6 +86,8 @@ public class WSSecEncrypt extends WSSecE
     private boolean encKeyIdDirectId;
     
     private boolean embedEncryptedKey;
+
+    private List<Element> attachmentEncryptedDataElements;
  
     public WSSecEncrypt() {
         super();
@@ -130,6 +139,8 @@ public class WSSecEncrypt extends WSSecE
             } 
             ephemeralKey = symmetricKey.getEncoded();
         }
+
+        attachmentEncryptedDataElements = new ArrayList<Element>();
         
         symmetricKey = KeyUtils.prepareSecretKey(symEncAlgo, ephemeralKey);
         
@@ -200,6 +211,8 @@ public class WSSecEncrypt extends WSSecE
         }
         
         Element refs = encryptForRef(null, parts);
+
+        addAttachmentEncryptedDataElements(secHeader);
         if (encryptedKeyElement != null) {
             addInternalRefElement(refs);
             prependToHeader(secHeader); 
@@ -248,7 +261,8 @@ public class WSSecEncrypt extends WSSecE
         SecretKeySpec secretKeySpec = new SecretKeySpec(symmetricKey.getEncoded(), symmetricKey.getAlgorithm());
         List<String> encDataRefs = 
             doEncryption(
-                document, getWsConfig(), keyInfo, secretKeySpec, symEncAlgo, references, callbackLookup
+                document, getWsConfig(), keyInfo, secretKeySpec, symEncAlgo, references, callbackLookup,
+                    attachmentCallbackHandler, attachmentEncryptedDataElements
             );
         if (dataRef == null) {
             dataRef = 
@@ -296,6 +310,17 @@ public class WSSecEncrypt extends WSSecE
         WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), dataRef);
     }
 
+    public void addAttachmentEncryptedDataElements(WSSecHeader secHeader) {
+        if (attachmentEncryptedDataElements != null) {
+            for (int i = 0; i < attachmentEncryptedDataElements.size(); i++) {
+                Element encryptedData = attachmentEncryptedDataElements.get(i);
+                WSSecurityUtil.prependChildElement(
+                        secHeader.getSecurityHeader(), encryptedData
+                );
+            }
+        }
+    }
+
     /**
      * Perform encryption on the SOAP envelope.
      * @param doc The document containing the SOAP envelope as document element
@@ -316,6 +341,22 @@ public class WSSecEncrypt extends WSSecE
         List<WSEncryptionPart> references,
         CallbackLookup callbackLookup
     ) throws WSSecurityException {
+        return doEncryption(
+                doc, config, keyInfo, secretKey, encryptionAlgorithm,
+                references, callbackLookup, null, null);
+    }
+
+    public static List<String> doEncryption(
+            Document doc,
+            WSSConfig config,
+            KeyInfo keyInfo,
+            SecretKey secretKey,
+            String encryptionAlgorithm,
+            List<WSEncryptionPart> references,
+            CallbackLookup callbackLookup,
+            CallbackHandler attachmentCallbackHandler,
+            List<Element> attachmentEncryptedDataElements
+    ) throws WSSecurityException {
 
         XMLCipher xmlCipher = null;
         try {
@@ -329,6 +370,11 @@ public class WSSecEncrypt extends WSSecE
         List<String> encDataRef = new ArrayList<String>();
         for (int part = 0; part < references.size(); part++) {
             WSEncryptionPart encPart = references.get(part);
+
+            if ("cid:Attachments".equals(encPart.getId())) {
+                continue;
+            }
+
             //
             // Get the data to encrypt.
             //
@@ -347,10 +393,9 @@ public class WSSecEncrypt extends WSSecE
                     "{" + encPart.getNamespace() + "}" + encPart.getName());
             }
 
-            String modifier = encPart.getEncModifier();
             for (Element elementToEncrypt : elementsToEncrypt) {
                 String id = 
-                    encryptElement(doc, elementToEncrypt, modifier, config, xmlCipher, 
+                    encryptElement(doc, elementToEncrypt, encPart.getEncModifier(), config, xmlCipher,
                                    secretKey, keyInfo);
                 encPart.setEncId(id);
                 encDataRef.add("#" + id);
@@ -366,9 +411,132 @@ public class WSSecEncrypt extends WSSecE
                 }
             }
         }
+
+        for (int part = 0; part < references.size(); part++) {
+            WSEncryptionPart encPart = references.get(part);
+
+            if ("cid:Attachments".equals(encPart.getId())) {
+
+                if (attachmentCallbackHandler == null) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILURE,
+                            "empty", "no attachment callbackhandler supplied"
+                    );
+                }
+
+                AttachmentRequestCallback attachmentRequestCallback = new AttachmentRequestCallback();
+                try {
+                    attachmentCallbackHandler.handle(new Callback[]{attachmentRequestCallback});
+                } catch (Exception e) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILED_ENCRYPTION, e
+                    );
+                }
+                List<Attachment> attachments = attachmentRequestCallback.getAttachments();
+                if (attachments == null || attachments.isEmpty()) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILURE,
+                            "noEncElement"
+                    );
+                }
+
+                String attachmentEncryptedDataType;
+                if ("Element".equals(encPart.getEncModifier())) {
+                    attachmentEncryptedDataType = WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_COMPLETE;
+                } else {
+                    attachmentEncryptedDataType = WSConstants.SWA_ATTACHMENT_ENCRYPTED_DATA_TYPE_CONTENT_ONLY;
+                }
+
+                for (int i = 0; i < attachments.size(); i++) {
+                    Attachment attachment = attachments.get(i);
+
+                    final String attachmentId = attachment.getId();
+                    String encEncryptedDataId = config.getIdAllocator().createId("ED-", attachmentId);
+                    encDataRef.add("#" + encEncryptedDataId);
+
+                    Element encryptedData =
+                            doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptedData");
+                    encryptedData.setAttributeNS(null, "Id", encEncryptedDataId);
+                    encryptedData.setAttributeNS(null, "MimeType", attachment.getMimeType());
+                    encryptedData.setAttributeNS(null, "Type", attachmentEncryptedDataType);
+
+                    Element encryptionMethod =
+                            doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptionMethod");
+                    encryptionMethod.setAttributeNS(null, "Algorithm", encryptionAlgorithm);
+
+                    encryptedData.appendChild(encryptionMethod);
+                    encryptedData.appendChild(keyInfo.getElement());
+
+                    Element cipherData =
+                            doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherData");
+                    Element cipherReference =
+                            doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherReference");
+                    cipherReference.setAttributeNS(null, "URI", "cid:" + attachmentId);
+
+                    Element transforms = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":Transforms");
+                    Element transform = doc.createElementNS(WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":Transform");
+                    transform.setAttributeNS(null, "Algorithm", WSConstants.SWA_ATTACHMENT_CIPHERTEXT_TRANS);
+                    transforms.appendChild(transform);
+
+                    cipherReference.appendChild(transforms);
+                    cipherData.appendChild(cipherReference);
+                    encryptedData.appendChild(cipherData);
+
+                    attachmentEncryptedDataElements.add(encryptedData);
+
+                    Attachment resultAttachment = new Attachment();
+                    resultAttachment.setId(attachmentId);
+                    resultAttachment.setMimeType("application/octet-stream");
+
+                    String jceAlgorithm = JCEMapper.translateURItoJCEID(encryptionAlgorithm);
+                    Cipher cipher = null;
+                    try {
+                        cipher = Cipher.getInstance(jceAlgorithm);
+
+                        // The Spec mandates a 96-bit IV for GCM algorithms
+                        if (XMLCipher.AES_128_GCM.equals(encryptionAlgorithm)
+                                || XMLCipher.AES_192_GCM.equals(encryptionAlgorithm)
+                                || XMLCipher.AES_256_GCM.equals(encryptionAlgorithm)) {
+                            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+                            byte[] temp = new byte[12];
+                            random.nextBytes(temp);
+                            IvParameterSpec paramSpec = new IvParameterSpec(temp);
+                            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
+                        } else {
+                            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
+                        }
+                    } catch (Exception e) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, e);
+                    }
+
+                    Map<String, String> headers = new HashMap<String, String>();
+                    headers.putAll(attachment.getHeaders());
+                    resultAttachment.setSourceStream(
+                            AttachmentUtils.setupAttachmentEncryptionStream(
+                                    cipher,
+                                    "Element".equals(encPart.getEncModifier()),
+                                    attachment,
+                                    headers
+                            )
+                    );
+                    resultAttachment.addHeaders(headers);
+
+                    AttachmentResultCallback attachmentResultCallback = new AttachmentResultCallback();
+                    attachmentResultCallback.setAttachmentId(attachmentId);
+                    attachmentResultCallback.setAttachment(resultAttachment);
+                    try {
+                        attachmentCallbackHandler.handle(new Callback[]{attachmentResultCallback});
+                    } catch (Exception e) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, e);
+                    }
+                }
+                break;
+            }
+        }
+
         return encDataRef;
     }
-    
+
     /**
      * Encrypt an element.
      */

Modified: webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureBase.java
URL: http://svn.apache.org/viewvc/webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureBase.java?rev=1540772&r1=1540771&r2=1540772&view=diff
==============================================================================
--- webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureBase.java (original)
+++ webservices/wss4j/trunk/ws-security-dom/src/main/java/org/apache/wss4j/dom/message/WSSecSignatureBase.java Mon Nov 11 16:54:52 2013
@@ -19,22 +19,13 @@
 
 package org.apache.wss4j.dom.message;
 
-import org.apache.wss4j.dom.WSConstants;
-import org.apache.wss4j.dom.WSDocInfo;
-import org.apache.wss4j.dom.WSSConfig;
-import org.apache.wss4j.common.WSEncryptionPart;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.dom.transform.STRTransform;
-import org.apache.wss4j.dom.util.WSSecurityUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
+import java.security.InvalidAlgorithmParameterException;
+import java.security.NoSuchAlgorithmException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import javax.security.auth.callback.Callback;
 import javax.xml.crypto.XMLStructure;
 import javax.xml.crypto.dom.DOMStructure;
 import javax.xml.crypto.dsig.DigestMethod;
@@ -43,6 +34,21 @@ import javax.xml.crypto.dsig.XMLSignatur
 import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;
 import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 
+import org.apache.wss4j.common.WSEncryptionPart;
+import org.apache.wss4j.common.ext.Attachment;
+import org.apache.wss4j.common.ext.AttachmentRequestCallback;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.dom.WSConstants;
+import org.apache.wss4j.dom.WSDocInfo;
+import org.apache.wss4j.dom.WSSConfig;
+import org.apache.wss4j.dom.transform.AttachmentTransformParameterSpec;
+import org.apache.wss4j.dom.transform.STRTransform;
+import org.apache.wss4j.dom.util.WSSecurityUtil;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
 /**
  * This is the base class for WS Security messages that are used for signature generation or
  * verification.
@@ -90,9 +96,84 @@ public class WSSecSignatureBase extends 
                 WSSecurityException.ErrorCode.FAILED_SIGNATURE, "noXMLSig", ex
             );
         }
-        
-        List<javax.xml.crypto.dsig.Reference> referenceList = 
-            new ArrayList<javax.xml.crypto.dsig.Reference>();
+
+        //create separate list for attachment and append it after same document references
+        //are processed.
+        List<javax.xml.crypto.dsig.Reference> attachmentReferenceList = new ArrayList<javax.xml.crypto.dsig.Reference>();
+
+        for (WSEncryptionPart encPart : references) {
+            if ("cid:Attachments".equals(encPart.getId())) {
+
+                if (attachmentCallbackHandler == null) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILURE,
+                            "empty", "no attachment callbackhandler supplied"
+                    );
+                }
+
+                AttachmentRequestCallback attachmentRequestCallback = new AttachmentRequestCallback();
+                //no mime type must be set for signature:
+                //attachmentCallback.setResultingMimeType(null);
+                try {
+                    attachmentCallbackHandler.handle(new Callback[]{attachmentRequestCallback});
+                } catch (Exception e) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILURE, e
+                    );
+                }
+                List<Attachment> attachments = attachmentRequestCallback.getAttachments();
+                if (attachments == null || attachments.isEmpty()) {
+                    throw new WSSecurityException(
+                            WSSecurityException.ErrorCode.FAILURE,
+                            "noEncElement"
+                    );
+                }
+
+                for (int i = 0; i < attachments.size(); i++) {
+                    Attachment attachment = attachments.get(i);
+
+                    try {
+                        List<Transform> transforms = new ArrayList<Transform>();
+
+                        AttachmentTransformParameterSpec attachmentTransformParameterSpec =
+                                new AttachmentTransformParameterSpec(
+                                        attachmentCallbackHandler,
+                                        attachment
+                                        );
+
+                        String attachmentSignatureTransform;
+                        if ("Element".equals(encPart.getEncModifier())) {
+                            attachmentSignatureTransform = WSConstants.SWA_ATTACHMENT_COMPLETE_SIG_TRANS;
+                        } else {
+                            attachmentSignatureTransform = WSConstants.SWA_ATTACHMENT_CONTENT_SIG_TRANS;
+                        }
+
+                        transforms.add(
+                                signatureFactory.newTransform(
+                                        attachmentSignatureTransform,
+                                        attachmentTransformParameterSpec)
+                        );
+
+                        javax.xml.crypto.dsig.Reference reference =
+                                signatureFactory.newReference("cid:" + attachment.getId(),
+                                        digestMethod,
+                                        transforms,
+                                        null,
+                                        null
+                                );
+
+                        attachmentReferenceList.add(reference);
+                    } catch (InvalidAlgorithmParameterException e) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e);
+                    } catch (NoSuchAlgorithmException e) {
+                        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e);
+                    }
+                }
+                break;
+            }
+        }
+
+        List<javax.xml.crypto.dsig.Reference> referenceList = new ArrayList<javax.xml.crypto.dsig.Reference>();
 
         for (WSEncryptionPart encPart : references) {
             String idToSign = encPart.getId();
@@ -104,6 +185,10 @@ public class WSSecSignatureBase extends 
             // names: "STRTransform": Setup the ds:Reference to use STR Transform
             //
             try {
+                //attachments are already processed in the above loop
+                if ("cid:Attachments".equals(idToSign)) {
+                    continue;
+                }
                 if (idToSign != null) {
                     Transform transform = null;
                     if ("STRTransform".equals(elemName)) {
@@ -198,7 +283,8 @@ public class WSSecSignatureBase extends 
                 );
             }
         }
-        
+        //append attachment references now
+        referenceList.addAll(attachmentReferenceList);
         return referenceList;
     }