1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.ws.security.message;
21  
22  import org.apache.ws.security.SOAPConstants;
23  import org.apache.ws.security.WSConstants;
24  import org.apache.ws.security.WSSConfig;
25  import org.apache.ws.security.WSSecurityEngine;
26  import org.apache.ws.security.WSEncryptionPart;
27  import org.apache.ws.security.WSSecurityEngineResult;
28  import org.apache.ws.security.WSDataRef;
29  import org.apache.ws.security.WSSecurityException;
30  import org.apache.ws.security.common.CustomHandler;
31  import org.apache.ws.security.common.KeystoreCallbackHandler;
32  import org.apache.ws.security.common.SecretKeyCallbackHandler;
33  import org.apache.ws.security.common.SOAPUtil;
34  import org.apache.ws.security.components.crypto.Crypto;
35  import org.apache.ws.security.components.crypto.CryptoFactory;
36  import org.apache.ws.security.handler.RequestData;
37  import org.apache.ws.security.handler.WSHandlerConstants;
38  import org.apache.ws.security.str.STRParser.REFERENCE_TYPE;
39  import org.apache.ws.security.util.Base64;
40  import org.apache.ws.security.util.WSSecurityUtil;
41  import org.w3c.dom.Document;
42  import org.w3c.dom.Element;
43  
44  import javax.crypto.KeyGenerator;
45  import javax.crypto.SecretKey;
46  import javax.security.auth.callback.CallbackHandler;
47  
48  import java.util.ArrayList;
49  import java.util.List;
50  
51  /**
52   * A set of test-cases for encrypting and decrypting SOAP requests.
53   *
54   * @author Davanum Srinivas (dims@yahoo.com)
55   * @author Werner Dittmann (werner@apache.org)
56   */
57  public class EncryptionTest extends org.junit.Assert {
58      private static final org.apache.commons.logging.Log LOG = 
59          org.apache.commons.logging.LogFactory.getLog(EncryptionTest.class);
60      private static final javax.xml.namespace.QName SOAP_BODY =
61          new javax.xml.namespace.QName(
62              WSConstants.URI_SOAP11_ENV,
63              "Body"
64          );
65  
66      private WSSecurityEngine secEngine = new WSSecurityEngine();
67      private CallbackHandler keystoreCallbackHandler = new KeystoreCallbackHandler();
68      private SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
69      private byte[] keyData;
70      private SecretKey key;
71      private Crypto crypto = null;
72      
73      public EncryptionTest() throws Exception {
74          crypto = CryptoFactory.getInstance("wss40.properties");
75      }
76      
77      /**
78       * Setup method
79       * 
80       * @throws java.lang.Exception Thrown when there is a problem in setup
81       */
82      @org.junit.Before
83      public void setUp() throws Exception {
84          KeyGenerator keyGen = KeyGenerator.getInstance("AES");
85          keyGen.init(128);
86          key = keyGen.generateKey();
87          keyData = key.getEncoded();
88          WSSConfig wssConfig = WSSConfig.getNewInstance();
89          wssConfig.setWsiBSPCompliant(true);
90          secEngine.setWssConfig(wssConfig);
91      }
92  
93      /**
94       * Test that encrypt and decrypt a WS-Security envelope.
95       * This test uses the RSA_15 algorithm to transport (wrap) the symmetric
96       * key.
97       * <p/>
98       * 
99       * @throws Exception Thrown when there is any problem in signing or verification
100      */
101     @org.junit.Test
102     public void testEncryptionDecryptionRSA15() throws Exception {
103         WSSecEncrypt builder = new WSSecEncrypt();
104         builder.setUserInfo("wss40");
105         builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
106         builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
107         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
108         WSSecHeader secHeader = new WSSecHeader();
109         secHeader.insertSecurityHeader(doc);
110         LOG.info("Before Encryption Triple DES....");
111         Document encryptedDoc = builder.build(doc, crypto, secHeader);
112         LOG.info("After Encryption Triple DES....");
113 
114         String outputString = 
115             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
116         if (LOG.isDebugEnabled()) {
117             LOG.debug("Encrypted message, RSA-15 keytransport, 3DES:");
118             LOG.debug(outputString);
119         }
120         assertTrue(outputString.indexOf("counter_port_type") == -1 ? true : false);
121         verify(encryptedDoc, keystoreCallbackHandler, SOAP_BODY);
122 
123         /*
124          * second run, same Junit set up, but change encryption method, 
125          * key identification, encryption mode (Element now), and data to encrypt.
126          * This tests if several runs of different algorithms on same builder/cipher 
127          * setup are ok.
128          */
129         builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
130         builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
131         builder.setSymmetricKey(null);
132         java.util.List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
133         WSEncryptionPart encP = 
134             new WSEncryptionPart(
135                 "add", "http://ws.apache.org/counter/counter_port_type", "Element"
136             );
137         parts.add(encP);
138         builder.setParts(parts);
139         doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
140         secHeader = new WSSecHeader();
141         secHeader.insertSecurityHeader(doc);        
142         LOG.info("Before Encryption AES 128/RSA-15....");
143         encryptedDoc = builder.build(doc, crypto, secHeader);
144         LOG.info("After Encryption AES 128/RSA-15....");
145         outputString = 
146             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
147         if (LOG.isDebugEnabled()) {
148             LOG.debug("Encrypted message, RSA-15 keytransport, AES 128:");
149             LOG.debug(outputString);
150         }
151         assertTrue(outputString.indexOf("counter_port_type") == -1 ? true : false);
152         List<WSSecurityEngineResult> results = verify(
153             encryptedDoc,
154             keystoreCallbackHandler,
155             new javax.xml.namespace.QName(
156                 "http://ws.apache.org/counter/counter_port_type",
157                 "add"
158             )
159         );
160         
161         WSSecurityEngineResult actionResult =
162                 WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
163         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE));
164         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE));
165         REFERENCE_TYPE referenceType = 
166             (REFERENCE_TYPE)actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE);
167         assertTrue(referenceType == REFERENCE_TYPE.ISSUER_SERIAL);
168     }
169 
170     /**
171      * Test that encrypt and decrypt a WS-Security envelope.
172      * This test uses the RSA OAEP algorithm to transport (wrap) the symmetric
173      * key.
174      * <p/>
175      * 
176      * @throws Exception Thrown when there is any problem in signing or verification
177      */
178     @org.junit.Test
179     public void testEncryptionDecryptionOAEP() throws Exception {
180         WSSecEncrypt builder = new WSSecEncrypt();
181         builder.setUserInfo("wss40");
182         builder.setKeyIdentifierType(WSConstants.X509_KEY_IDENTIFIER);
183         builder.setKeyEnc(WSConstants.KEYTRANSPORT_RSAOEP);
184         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
185         WSSecHeader secHeader = new WSSecHeader();
186         secHeader.insertSecurityHeader(doc);        
187         LOG.info("Before Encryption Triple DES/RSA-OAEP....");
188         Document encryptedDoc = builder.build(doc, crypto, secHeader);
189         LOG.info("After Encryption Triple DES/RSA-OAEP....");
190 
191         String outputString = 
192             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
193         if (LOG.isDebugEnabled()) {
194             LOG.debug("Encrypted message, RSA-OAEP keytransport, 3DES:");
195             LOG.debug(outputString);
196         }
197         assertTrue(outputString.indexOf("counter_port_type") == -1 ? true : false);
198         
199         // Turn off BSP spec compliance
200         WSSecurityEngine newEngine = new WSSecurityEngine();
201         WSSConfig config = WSSConfig.getNewInstance();
202         config.setWsiBSPCompliant(false);
203         newEngine.setWssConfig(config);
204         List<WSSecurityEngineResult> results = 
205             newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
206         
207         WSSecurityEngineResult actionResult =
208                 WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
209         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE));
210         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE));
211         REFERENCE_TYPE referenceType = 
212             (REFERENCE_TYPE)actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE);
213         assertTrue(referenceType == REFERENCE_TYPE.KEY_IDENTIFIER);
214         
215         // Now turn on BSP spec compliance
216         config.setWsiBSPCompliant(true);
217         newEngine.setWssConfig(config);
218         try {
219             newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
220             fail("Failure expected on a bad ValueType attribute");
221         } catch (WSSecurityException ex) {
222             // expected
223         }
224 
225     }
226     
227     /**
228      * Test that encrypt and then again encrypts (Super encryption) WS-Security
229      * envelope and then verifies it <p/>
230      * 
231      * @throws Exception
232      *             Thrown when there is any problem in encryption or
233      *             verification
234      */
235     @org.junit.Test
236     public void testEncryptionEncryption() throws Exception {
237         Crypto encCrypto = CryptoFactory.getInstance();
238         WSSecEncrypt encrypt = new WSSecEncrypt();
239         encrypt.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
240         LOG.info("Before Encryption....");
241         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
242         WSSecHeader secHeader = new WSSecHeader();
243         secHeader.insertSecurityHeader(doc);
244 
245         Document encryptedDoc = encrypt.build(doc, encCrypto, secHeader);
246         
247         if (LOG.isDebugEnabled()) {
248             LOG.debug("After the first encryption:");
249             String outputString = 
250                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
251             LOG.debug(outputString);
252         }
253         
254         Document encryptedEncryptedDoc = encrypt.build(encryptedDoc, encCrypto, secHeader);
255         
256         if (LOG.isDebugEnabled()) {
257             LOG.debug("After the second encryption:");
258             String outputString = 
259                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedEncryptedDoc);
260             LOG.debug(outputString);
261         }
262 
263         LOG.info("After Encryption....");
264         verify(encryptedEncryptedDoc, encCrypto, keystoreCallbackHandler);
265     }
266     
267     /**
268      * Test that encrypts and decrypts a WS-Security envelope.
269      * The test uses the ThumbprintSHA1 key identifier type. 
270      * <p/>
271      * 
272      * @throws java.lang.Exception Thrown when there is any problem in encryption or decryption
273      */
274     @org.junit.Test
275     public void testX509EncryptionThumb() throws Exception {
276         Crypto encCrypto = CryptoFactory.getInstance();
277         WSSecEncrypt builder = new WSSecEncrypt();
278         builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
279         builder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
280         
281         LOG.info("Before Encrypting ThumbprintSHA1....");
282         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
283         WSSecHeader secHeader = new WSSecHeader();
284         secHeader.insertSecurityHeader(doc);        
285         Document encryptedDoc = builder.build(doc, encCrypto, secHeader);
286         
287         String outputString = 
288             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
289         if (LOG.isDebugEnabled()) {
290             LOG.debug("Encrypted message with THUMBPRINT_IDENTIFIER:");
291             LOG.debug(outputString);
292         }
293         assertTrue(outputString.indexOf("#ThumbprintSHA1") != -1);
294     
295         LOG.info("After Encrypting ThumbprintSHA1....");
296         List<WSSecurityEngineResult> results = verify(encryptedDoc, encCrypto, keystoreCallbackHandler);
297         
298         WSSecurityEngineResult actionResult =
299                 WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
300         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE));
301         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE));
302         REFERENCE_TYPE referenceType = 
303             (REFERENCE_TYPE)actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE);
304         assertTrue(referenceType == REFERENCE_TYPE.THUMBPRINT_SHA1);
305     }
306     
307     /**
308      * Test that encrypts and decrypts a WS-Security envelope.
309      * The test uses the EncryptedKeySHA1 key identifier type. 
310      * <p/>
311      * 
312      * @throws java.lang.Exception Thrown when there is any problem in encryption or decryption
313      */
314     @org.junit.Test
315     public void testX509EncryptionSHA1() throws Exception {
316         Crypto encCrypto = CryptoFactory.getInstance();
317         WSSecEncrypt builder = new WSSecEncrypt();
318         builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
319         builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
320      
321         LOG.info("Before Encrypting EncryptedKeySHA1....");
322         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
323         WSSecHeader secHeader = new WSSecHeader();
324         secHeader.insertSecurityHeader(doc);        
325         Document encryptedDoc = builder.build(doc, encCrypto, secHeader);
326      
327         String outputString = 
328             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
329         if (LOG.isDebugEnabled()) {
330             LOG.debug("Encrypted message with ENCRYPTED_KEY_SHA1_IDENTIFIER:");
331             LOG.debug(outputString);
332         }
333         assertTrue(outputString.indexOf("#EncryptedKeySHA1") != -1);
334      
335         LOG.info("After Encrypting EncryptedKeySHA1....");
336         verify(encryptedDoc, encCrypto, keystoreCallbackHandler);
337     }
338     
339     /**
340      * Test that encrypts using EncryptedKeySHA1, where it uses a symmetric key, rather than a 
341      * generated session key which is then encrypted using a public key.
342      * 
343      * @throws java.lang.Exception Thrown when there is any problem in encryption or decryption
344      */
345     @org.junit.Test
346     public void testEncryptionSHA1Symmetric() throws Exception {
347         WSSecEncrypt builder = new WSSecEncrypt();
348         builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
349         builder.setSymmetricKey(key);
350         builder.setEncryptSymmKey(false);
351         
352         LOG.info("Before Encrypting EncryptedKeySHA1....");
353         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
354         WSSecHeader secHeader = new WSSecHeader();
355         secHeader.insertSecurityHeader(doc);
356         Document encryptedDoc = builder.build(doc, crypto, secHeader);
357         
358         byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
359         String identifier = Base64.encode(encodedBytes);
360         secretKeyCallbackHandler.addSecretKey(identifier, keyData);
361      
362         String outputString = 
363             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
364         if (LOG.isDebugEnabled()) {
365             LOG.debug("Encrypted message with ENCRYPTED_KEY_SHA1_IDENTIFIER:");
366             LOG.debug(outputString);
367         }
368         assertTrue(outputString.indexOf("#EncryptedKeySHA1") != -1);
369      
370         LOG.info("After Encrypting EncryptedKeySHA1....");
371         verify(encryptedDoc, (Crypto)null, secretKeyCallbackHandler);
372     }
373     
374     /**
375      * Test that encrypts using EncryptedKeySHA1, where it uses a symmetric key (bytes), 
376      * rather than a generated session key which is then encrypted using a public key.
377      * 
378      * @throws java.lang.Exception Thrown when there is any problem in encryption or decryption
379      */
380     @org.junit.Test
381     public void testEncryptionSHA1SymmetricBytes() throws Exception {
382         WSSecEncrypt builder = new WSSecEncrypt();
383         builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
384         builder.setEphemeralKey(keyData);
385         builder.setEncryptSymmKey(false);
386         
387         LOG.info("Before Encrypting EncryptedKeySHA1....");
388         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
389         WSSecHeader secHeader = new WSSecHeader();
390         secHeader.insertSecurityHeader(doc);        
391         Document encryptedDoc = builder.build(doc, crypto, secHeader);
392         
393         byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
394         String identifier = Base64.encode(encodedBytes);
395         secretKeyCallbackHandler.addSecretKey(identifier, keyData);
396      
397         String outputString = 
398             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
399         if (LOG.isDebugEnabled()) {
400             LOG.debug("Encrypted message with ENCRYPTED_KEY_SHA1_IDENTIFIER:");
401             LOG.debug(outputString);
402         }
403         assertTrue(outputString.indexOf("#EncryptedKeySHA1") != -1);
404      
405         LOG.info("After Encrypting EncryptedKeySHA1....");
406         verify(encryptedDoc, crypto, secretKeyCallbackHandler);
407     }
408     
409     
410     /**
411      * Test that encrypts using EncryptedKeySHA1, where it uses a symmetric key, rather than a 
412      * generated session key which is then encrypted using a public key. The request is generated
413      * using WSHandler, instead of coding it.
414      * 
415      * @throws java.lang.Exception Thrown when there is any problem in encryption or decryption
416      */
417     @org.junit.Test
418     public void testEncryptionSHA1SymmetricBytesHandler() throws Exception {
419         final WSSConfig cfg = WSSConfig.getNewInstance();
420         final RequestData reqData = new RequestData();
421         reqData.setWssConfig(cfg);
422         java.util.Map<String, Object> messageContext = new java.util.TreeMap<String, Object>();
423         messageContext.put(WSHandlerConstants.ENC_SYM_ENC_KEY, "false");
424         messageContext.put(WSHandlerConstants.ENC_KEY_ID, "EncryptedKeySHA1");
425         secretKeyCallbackHandler.setOutboundSecret(keyData);
426         messageContext.put(WSHandlerConstants.PW_CALLBACK_REF, secretKeyCallbackHandler);
427         reqData.setMsgContext(messageContext);
428         reqData.setUsername("");
429         
430         final java.util.List<Integer> actions = new java.util.ArrayList<Integer>();
431         actions.add(Integer.valueOf(WSConstants.ENCR));
432         final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
433         CustomHandler handler = new CustomHandler();
434         handler.send(
435             WSConstants.ENCR, 
436             doc, 
437             reqData, 
438             actions,
439             true
440         );
441         
442         String outputString = 
443             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
444         if (LOG.isDebugEnabled()) {
445             LOG.debug(outputString);
446         }
447         
448         verify(doc, (Crypto)null, secretKeyCallbackHandler);
449     }
450     
451     /**
452      * Test that encrypt and decrypt a WS-Security envelope.
453      * 
454      * This test uses the RSA_15 algorithm to transport (wrap) the symmetric key.
455      * The test case creates a ReferenceList element that references EncryptedData
456      * elements. The ReferencesList element is put into the Security header, not
457      * as child of the EncryptedKey. The EncryptedData elements contain a KeyInfo
458      * that references the EncryptedKey via a STR/Reference structure.
459      * 
460      * Refer to OASIS WS Security spec 1.1, chap 7.7
461      */
462     @org.junit.Test
463     public void testEncryptionDecryptionRSA15STR() throws Exception {
464         WSSecEncrypt builder = new WSSecEncrypt();
465         builder.setUserInfo("wss40");
466         builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
467         builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
468         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
469         WSSecHeader secHeader = new WSSecHeader();
470         secHeader.insertSecurityHeader(doc);
471         LOG.info("Before Encryption Triple DES....");
472 
473         /*
474          * Prepare the Encrypt object with the token, setup data structure
475          */
476         builder.prepare(doc, crypto);
477 
478         /*
479          * Set up the parts structure to encrypt the body
480          */
481         SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
482                 .getDocumentElement());
483         java.util.List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
484         WSEncryptionPart encP = new WSEncryptionPart(soapConstants
485                 .getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(),
486                 "Content");
487         parts.add(encP);
488 
489         /*
490          * Encrypt the parts (Body), create EncryptedData elements that reference
491          * the EncryptedKey, and get a ReferenceList that can be put into the
492          * Security header. Be sure that the ReferenceList is after the
493          * EncryptedKey element in the Security header (strict layout)
494          */
495         Element refs = builder.encryptForRef(null, parts);
496         builder.addExternalRefElement(refs, secHeader);
497 
498         /*
499          * now add (prepend) the EncryptedKey element, then a
500          * BinarySecurityToken if one was setup during prepare
501          */
502         builder.prependToHeader(secHeader);
503 
504         builder.prependBSTElementToHeader(secHeader);
505 
506         Document encryptedDoc = doc;
507         LOG.info("After Encryption Triple DES....");
508 
509         String outputString = 
510             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
511         if (LOG.isDebugEnabled()) {
512             LOG.debug("Encrypted message, RSA-15 keytransport, 3DES:");
513             LOG.debug(outputString);
514         }
515         assertTrue(outputString.indexOf("counter_port_type") == -1 ? true
516                 : false);
517         List<WSSecurityEngineResult> results = verify(encryptedDoc, crypto, keystoreCallbackHandler);
518         
519         outputString = 
520             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
521         assertTrue(outputString.indexOf("counter_port_type") > 0 ? true
522                 : false);
523         
524         WSSecurityEngineResult actionResult =
525                 WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
526         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE));
527         assertNotNull(actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE));
528         REFERENCE_TYPE referenceType = 
529             (REFERENCE_TYPE)actionResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE);
530         assertTrue(referenceType == REFERENCE_TYPE.DIRECT_REF);
531     }
532     
533     
534     @org.junit.Test
535     public void testBadAttribute() throws Exception {
536         WSSecEncrypt builder = new WSSecEncrypt();
537         builder.setUserInfo("wss40");
538         builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
539         builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
540         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
541         WSSecHeader secHeader = new WSSecHeader();
542         secHeader.insertSecurityHeader(doc);
543 
544         /*
545          * Prepare the Encrypt object with the token, setup data structure
546          */
547         builder.prepare(doc, crypto);
548 
549         /*
550          * Set up the parts structure to encrypt the body
551          */
552         SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
553                 .getDocumentElement());
554         java.util.List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
555         WSEncryptionPart encP = new WSEncryptionPart(soapConstants
556                 .getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(),
557                 "Content");
558         parts.add(encP);
559 
560         /*
561          * Encrypt the parts (Body), create EncryptedData elements that reference
562          * the EncryptedKey, and get a ReferenceList that can be put into the
563          * Security header. Be sure that the ReferenceList is after the
564          * EncryptedKey element in the Security header (strict layout)
565          */
566         Element refs = builder.encryptForRef(null, parts);
567         builder.addExternalRefElement(refs, secHeader);
568 
569         /*
570          * now add (prepend) the EncryptedKey element, then a
571          * BinarySecurityToken if one was setup during prepare
572          */
573         Element encryptedKeyElement = builder.getEncryptedKeyElement();
574         encryptedKeyElement.setAttributeNS(null, "Type", "SomeType");
575         WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), encryptedKeyElement);
576 
577         builder.prependBSTElementToHeader(secHeader);
578 
579         Document encryptedDoc = doc;
580 
581         String outputString = 
582             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
583         if (LOG.isDebugEnabled()) {
584             LOG.debug(outputString);
585         }
586         
587         // Turn off BSP compliance
588         WSSecurityEngine newEngine = new WSSecurityEngine();
589         WSSConfig wssConfig = WSSConfig.getNewInstance();
590         wssConfig.setWsiBSPCompliant(false);
591         newEngine.setWssConfig(wssConfig);
592         newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
593         
594         // Now turn on BSP compliance
595         wssConfig.setWsiBSPCompliant(true);
596         newEngine.setWssConfig(wssConfig);
597         try {
598             newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
599             fail("Failure expected on a bad attribute type");
600         } catch (WSSecurityException ex) {
601             assertTrue(ex.getMessage().contains("bad attribute"));
602         }
603     }
604     
605     /**
606      * In this test an EncryptedKey structure is embedded in the EncryptedData structure.
607      * The EncryptedKey structure refers to a certificate via the SKI_KEY_IDENTIFIER.
608      */
609     @org.junit.Test
610     public void testEmbeddedEncryptedKey() throws Exception {
611         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
612         
613         WSSecEncrypt builder = new WSSecEncrypt();
614         builder.setUserInfo("wss40");
615         builder.setKeyIdentifierType(WSConstants.SKI_KEY_IDENTIFIER);
616         builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
617         builder.prepare(doc, crypto);
618         builder.setEmbedEncryptedKey(true);
619 
620         SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc
621                 .getDocumentElement());
622         java.util.List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
623         WSEncryptionPart encP = new WSEncryptionPart(soapConstants
624                 .getBodyQName().getLocalPart(), soapConstants.getEnvelopeURI(),
625                 "Content");
626         parts.add(encP);
627 
628         builder.encryptForRef(null, parts);
629 
630         String outputString = 
631             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
632         if (LOG.isDebugEnabled()) {
633             LOG.debug(outputString);
634         }
635         
636         verify(doc, crypto, keystoreCallbackHandler);
637     }
638 
639     /**
640      * Test that encrypt and decrypt a WS-Security envelope.
641      * This test uses the RSA OAEP algorithm to transport (wrap) the symmetric
642      * key and SHA-256.
643      * <p/>
644      * 
645      * @throws Exception Thrown when there is any problem in signing or verification
646      */
647     @org.junit.Test
648     public void testEncryptionDecryptionOAEPSHA256() throws Exception {
649         WSSecEncrypt builder = new WSSecEncrypt();
650         builder.setUserInfo("wss40");
651         builder.setKeyEnc(WSConstants.KEYTRANSPORT_RSAOEP);
652         builder.setDigestAlgorithm(WSConstants.SHA256);
653         Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
654         WSSecHeader secHeader = new WSSecHeader();
655         secHeader.insertSecurityHeader(doc);        
656         LOG.info("Before Encryption Triple DES/RSA-OAEP....");
657         Document encryptedDoc = builder.build(doc, crypto, secHeader);
658         LOG.info("After Encryption Triple DES/RSA-OAEP....");
659 
660         String outputString = 
661             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
662         if (LOG.isDebugEnabled()) {
663             LOG.debug("Encrypted message, RSA-OAEP keytransport, 3DES:");
664             LOG.debug(outputString);
665         }
666         assertTrue(outputString.indexOf("counter_port_type") == -1 ? true : false);
667         
668         WSSecurityEngine newEngine = new WSSecurityEngine();
669         List<WSSecurityEngineResult> results = 
670             newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
671         
672         WSSecurityEngineResult actionResult =
673                 WSSecurityUtil.fetchActionResult(results, WSConstants.ENCR);
674         assertNotNull(actionResult);
675     }
676     
677     /**
678      * Verifies the soap envelope <p/>
679      * 
680      * @param envelope
681      * @throws Exception
682      *             Thrown when there is a problem in verification
683      */
684     private List<WSSecurityEngineResult> verify(
685         Document doc, Crypto decCrypto, CallbackHandler handler
686     ) throws Exception {
687         List<WSSecurityEngineResult> results = 
688             secEngine.processSecurityHeader(doc, null, handler, decCrypto);
689         if (LOG.isDebugEnabled()) {
690             String outputString = 
691                 org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
692             LOG.debug(outputString);
693         }
694         return results;
695     }
696     
697     /**
698      * Verifies the soap envelope
699      * <p/>
700      * 
701      * @param envelope 
702      * @throws Exception Thrown when there is a problem in verification
703      */
704     @SuppressWarnings("unchecked")
705     private List<WSSecurityEngineResult> verify(
706         Document doc,
707         CallbackHandler handler,
708         javax.xml.namespace.QName expectedEncryptedElement
709     ) throws Exception {
710         final java.util.List<WSSecurityEngineResult> results = 
711             secEngine.processSecurityHeader(doc, null, handler, null, crypto);
712         String outputString = 
713             org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
714         if (LOG.isDebugEnabled()) {
715             LOG.debug(outputString);
716         }
717         assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false);
718         //
719         // walk through the results, and make sure there is an encryption
720         // action, together with a reference to the decrypted element 
721         // (as a QName)
722         //
723         boolean encrypted = false;
724         for (java.util.Iterator<WSSecurityEngineResult> ipos = results.iterator(); 
725             ipos.hasNext();) {
726             final WSSecurityEngineResult result = ipos.next();
727             final Integer action = (Integer) result.get(WSSecurityEngineResult.TAG_ACTION);
728             assertNotNull(action);
729             if ((action.intValue() & WSConstants.ENCR) != 0) {
730                 final java.util.List<WSDataRef> refs =
731                     (java.util.List<WSDataRef>) result.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
732                 assertNotNull(refs);
733                 encrypted = true;
734                 for (java.util.Iterator<WSDataRef> jpos = refs.iterator(); jpos.hasNext();) {
735                     final WSDataRef ref = jpos.next();
736                     assertNotNull(ref);
737                     assertNotNull(ref.getName());
738                     assertEquals(
739                         expectedEncryptedElement,
740                         ref.getName()
741                     );
742                     assertNotNull(ref.getProtectedElement());
743                     if (LOG.isDebugEnabled()) {
744                         LOG.debug("WSDataRef element: ");
745                         LOG.debug(
746                             org.apache.ws.security.util.DOM2Writer.nodeToString(
747                                 ref.getProtectedElement()
748                             )
749                         );
750                     }
751                 }
752             }
753         }
754         assertTrue(encrypted);
755         return results;
756     }
757 
758 }