Package com.sun.xml.wss.impl

Examples of com.sun.xml.wss.impl.SecurableSoapMessage


    throws PolicyGenerationException,NoSuchAlgorithmException,InvalidAlgorithmParameterException ,XWSSecurityException{
        SignaturePolicy signaturePolicy = (SignaturePolicy) fpContext.getSecurityPolicy();
        SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
        MLSPolicy keyBinding = signaturePolicy.getKeyBinding();
        XMLSignatureFactory signatureFactory = getSignatureFactory();
        SecurableSoapMessage secureMessage = fpContext.getSecurableSoapMessage();
        String canonicalAlgo = featureBinding.getCanonicalizationAlgorithm();
        boolean disableInclusivePrefix = featureBinding.getDisableInclusivePrefix();
        //String digestAlgo = featureBinding.getDigestAlgorithm();
        ArrayList targetList = featureBinding.getTargetBindings();
        String keyAlgo = null;
        String algo = MessageConstants.RSA_SHA1;
        if (fpContext.getAlgorithmSuite() != null) {
            algo = fpContext.getAlgorithmSuite().getSignatureAlgorithm();
        }

        keyAlgo = SecurityUtil.getKeyAlgo(algo);
               
        if(PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
            AuthenticationTokenPolicy.X509CertificateBinding certificateBinding =
                    (AuthenticationTokenPolicy.X509CertificateBinding)keyBinding;
            if (!"".equals(certificateBinding.getKeyAlgorithm())) {
                keyAlgo = certificateBinding.getKeyAlgorithm();
            }
        } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
            AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding =
                    (AuthenticationTokenPolicy.SAMLAssertionBinding)keyBinding;
            if (!"".equals(samlBinding.getKeyAlgorithm())) {
                keyAlgo = samlBinding.getKeyAlgorithm();
            }
        }else if(PolicyTypeUtil.symmetricKeyBinding(keyBinding)){
            SymmetricKeyBinding symmetricKeybinding = (SymmetricKeyBinding)keyBinding;
            if (!"".equals(symmetricKeybinding.getKeyAlgorithm())) {
                keyAlgo = symmetricKeybinding.getKeyAlgorithm();
            } else {
                keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
            }    
        } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
            keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
        } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(PolicyTypeUtil.issuedTokenKeyBinding(((DerivedTokenKeyBinding)keyBinding).getOriginalKeyBinding())){
               if(fpContext.getTrustContext().getProofKey() == null){
                   keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
               }                          
           }
       } else if (PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
           //TODO: verify if this is always correct
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(fpContext.getTrustContext().getProofKey() == null){
               keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
           }
       } else {
            logger.log(Level.SEVERE, LogStringsMessages.WSS_1335_UNSUPPORTED_KEYBINDING_SIGNATUREPOLICY());
            throw new XWSSecurityException("Unsupported KeyBinding for SignaturePolicy");
       }
       
        C14NMethodParameterSpec spec = null;
        if (MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.equalsIgnoreCase(canonicalAlgo)) {
            //List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
            //spec = new ExcC14NParameterSpec(inc);
            //NOTE: looking at BSP flag on sending side just for
            //ExC14N parameterList. Because XWSS11(xmlsec.jar) cannot
            //process the PrefixList, thereby breaking BC
            if (featureBinding.isBSP() || !disableInclusivePrefix) {
                List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
                spec = new ExcC14NParameterSpec(inc);
            } else {
                spec = null;
            }
View Full Code Here


    }
   
   
    Data dereferenceURI (String uri, XMLCryptoContext context) throws URIReferenceException, XWSSecurityException{
        FilterProcessingContext filterContext =(FilterProcessingContext) context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
        SecurableSoapMessage secureMsg = filterContext.getSecurableSoapMessage ();
        if(uri == null || uri.equals ("")){
            SOAPMessage msg = filterContext.getSOAPMessage ();
            Document doc = msg.getSOAPPart ();
            if(_constructor == null){
                return convertToData ((Node)doc,true);
            }else{
                try{
                    return (Data)_constructor.newInstance (new Object[] {doc,_false});
                }catch(Exception ex){
                    //throw new XWSSecurityException(ex);
                }
                return convertToData ((Node)doc,true);
            }
        }else if(uri.charAt (0) == '#'){
            return dereferenceFragment (secureMsg.getIdFromFragmentRef (uri),context);
        }else if(uri.startsWith ("cid:") || uri.startsWith ("attachmentRef:")){
            return dereferenceAttachments (uri,context);
        }else if(uri.startsWith ("http")){
            //throw new UnsupportedOperationException("Not yet supported ");
            return dereferenceExternalResource (uri,context);
View Full Code Here

    Data dereferenceExternalResource (final String uri,XMLCryptoContext context) throws URIReferenceException, XWSSecurityException {
       
        URIDereferencer resolver = WSSPolicyConsumerImpl.getInstance ().getDefaultResolver ();
        URIReference uriRef = null;
        FilterProcessingContext filterContext =(FilterProcessingContext) context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
        SecurableSoapMessage secureMsg = filterContext.getSecurableSoapMessage ();
        final Attr uriAttr = secureMsg.getSOAPMessage ().getSOAPPart ().createAttribute ("uri");
        uriAttr.setNodeValue (uri);
        uriRef = new DOMURIReference (){
           
            public String getURI (){
                return uri;
View Full Code Here

    Data dereferenceAttachments (String uri, XMLCryptoContext context) throws URIReferenceException, XWSSecurityException {
        boolean sunAttachmentTransformProvider = true;
        FilterProcessingContext filterContext =(FilterProcessingContext)
        context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
       
        SecurableSoapMessage secureMsg = filterContext.getSecurableSoapMessage ();
        AttachmentPart attachment = secureMsg.getAttachmentPart (uri);
        if(attachment == null){
            throw new URIReferenceException ("Attachment Resource with Identifier  "+uri+" was not found");
        }
        if(sunAttachmentTransformProvider){
            AttachmentData attachData = new AttachmentData ();
View Full Code Here

                    }
                }
                return convertToData ((Element)obj,true);
            }
        }
        SecurableSoapMessage secureMsg = filterContext.getSecurableSoapMessage ();
        Element element = secureMsg.getElementById (uri);
        if(element == null){
            throw new URIReferenceException ("Resource with fragment Identifier  "+uri+" was not found");
            //log;
        }
        if(_constructor == null){
View Full Code Here

         *    (3). Embedded Reference
         *    (4). X509 Issuer Serial
         */
        SecurityToken secToken = null;
        FilterProcessingContext filterContext = (FilterProcessingContext)context.get (MessageConstants.WSS_PROCESSING_CONTEXT);
        SecurableSoapMessage secureMessage = filterContext.getSecurableSoapMessage ();
        Document soapDocument = secureMessage.getSOAPPart ();
        SOAPElement soapElem =  XMLUtil.convertToSoapElement (soapDocument, (Element) element);
        SecurityTokenReference tokenRef = new SecurityTokenReference (soapElem);
        ReferenceElement refElement =  tokenRef.getReference ();
        HashMap tokenCache = filterContext.getTokenCache ();
        Element tokenElement = null;
        Element newElement = null;
       
        if (refElement instanceof DirectReference) {
            // isXMLToken = true;
            /* Use the URI value to locate the BST */
            String uri = ((DirectReference) refElement).getURI ();
            String tokenId = uri.substring (1);
            secToken = (SecurityToken)tokenCache.get (tokenId);
            if(secToken == null){
                tokenElement = secureMessage.getElementById (tokenId);
                if(tokenElement == null){
                    throw new URIReferenceException ("Could not locate token with following ID"+tokenId);
                }
            
            } else {
                tokenElement = secToken.getAsSoapElement();
            }
            newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
           
        } else if (refElement instanceof KeyIdentifier) {
            String valueType = ((KeyIdentifier) refElement).getValueType ();
            String keyId = ((KeyIdentifier) refElement).getReferenceValue ();
            if (MessageConstants.X509SubjectKeyIdentifier_NS.
                    equals (valueType) ||
                    MessageConstants.X509v3SubjectKeyIdentifier_NS.
                    equals (valueType)) {
                /* Use the Subject Key Identifier to locate BST */
                //  isXMLToken = false;
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509SubjectKeyIdentifier ){
                    if(token != null){
                        cert = ((X509SubjectKeyIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId));
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            } else if (MessageConstants.ThumbPrintIdentifier_NS.equals (valueType)) {
                X509Certificate cert = null;
               
                Object token = tokenCache.get (keyId);
                if(token instanceof X509ThumbPrintIdentifier ){
                    if(token != null){
                        cert = ((X509ThumbPrintIdentifier)token).getCertificate ();
                    }
                }
               
                if(cert == null){
                    cert = filterContext.getSecurityEnvironment ().getCertificate (
                            filterContext.getExtraneousProperties (), XMLUtil.getDecodedBase64EncodedData (keyId), MessageConstants.THUMB_PRINT_TYPE);
                }
                secToken = new X509SecurityToken (soapDocument, cert);
                tokenElement = secToken.getAsSoapElement ();
                newElement = tokenElement;
                //(Element)element.getOwnerDocument().importNode(tokenElement, true);
                try {
                    // EncodingType should not be set -
                    // As specified by WSS spec
                    newElement.removeAttribute ("EncodingType");
                } catch (DOMException de) {
                    logger.log(Level.SEVERE,com.sun.xml.wss.logging.LogStringsMessages.WSS_0607_STR_TRANSFORM_EXCEPTION());
                    throw new XWSSecurityRuntimeException (de.getMessage (), de);
                }
            }else if(MessageConstants.EncryptedKeyIdentifier_NS.equals (valueType)){
                // do something here
                newElement = null;
            } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType) ||
                     MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals (valueType)) {
               
                //TODO : should we first try locating from the cache
                if (tokenRef.getSamlAuthorityBinding () != null) {
                    tokenElement = filterContext.getSecurityEnvironment ().
                            locateSAMLAssertion (
                            filterContext.getExtraneousProperties(), tokenRef.getSamlAuthorityBinding (), keyId, secureMessage.getSOAPPart ());
                } else {
                    tokenElement = SAMLUtil.locateSamlAssertion (keyId,secureMessage.getSOAPPart ());
                }
                newElement = (Element)element.getOwnerDocument ().importNode (tokenElement, true);
               
                Assertion assertion = null;
                try {
View Full Code Here

    throws PolicyGenerationException,NoSuchAlgorithmException,InvalidAlgorithmParameterException ,XWSSecurityException{
        SignaturePolicy signaturePolicy = (SignaturePolicy) fpContext.getSecurityPolicy();
        SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
        MLSPolicy keyBinding = signaturePolicy.getKeyBinding();
        XMLSignatureFactory signatureFactory = getSignatureFactory();
        SecurableSoapMessage secureMessage = fpContext.getSecurableSoapMessage();
        String canonicalAlgo = featureBinding.getCanonicalizationAlgorithm();
        boolean disableInclusivePrefix = featureBinding.getDisableInclusivePrefix();
        //String digestAlgo = featureBinding.getDigestAlgorithm();
        ArrayList targetList = featureBinding.getTargetBindings();
        String keyAlgo = null;
        String algo = MessageConstants.RSA_SHA1;
        if (fpContext.getAlgorithmSuite() != null) {
            algo = fpContext.getAlgorithmSuite().getSignatureAlgorithm();
        }

        keyAlgo = SecurityUtil.getKeyAlgo(algo);
               
        if(PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
            AuthenticationTokenPolicy.X509CertificateBinding certificateBinding =
                    (AuthenticationTokenPolicy.X509CertificateBinding)keyBinding;
            if (!"".equals(certificateBinding.getKeyAlgorithm())) {
                keyAlgo = certificateBinding.getKeyAlgorithm();
            }
        } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
            AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding =
                    (AuthenticationTokenPolicy.SAMLAssertionBinding)keyBinding;
            if (!"".equals(samlBinding.getKeyAlgorithm())) {
                keyAlgo = samlBinding.getKeyAlgorithm();
            }
        }else if(PolicyTypeUtil.symmetricKeyBinding(keyBinding)){
            SymmetricKeyBinding symmetricKeybinding = (SymmetricKeyBinding)keyBinding;
            if (!"".equals(symmetricKeybinding.getKeyAlgorithm())) {
                keyAlgo = symmetricKeybinding.getKeyAlgorithm();
            } else {
                keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
            }    
        } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
            keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
        } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(PolicyTypeUtil.issuedTokenKeyBinding(((DerivedTokenKeyBinding)keyBinding).getOriginalKeyBinding())){
               if(fpContext.getTrustContext().getProofKey() == null){
                   keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
               }                          
           }
       } else if (PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
           //TODO: verify if this is always correct
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(fpContext.getTrustContext().getProofKey() == null){
               keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
           }
       } else {
            logger.log(Level.SEVERE, LogStringsMessages.WSS_1335_UNSUPPORTED_KEYBINDING_SIGNATUREPOLICY());
            throw new XWSSecurityException("Unsupported KeyBinding for SignaturePolicy");
       }
       
        C14NMethodParameterSpec spec = null;
        if (MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.equalsIgnoreCase(canonicalAlgo)) {
            //List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
            //spec = new ExcC14NParameterSpec(inc);
            //NOTE: looking at BSP flag on sending side just for
            //ExC14N parameterList. Because XWSS11(xmlsec.jar) cannot
            //process the PrefixList, thereby breaking BC
            if (featureBinding.isBSP() || !disableInclusivePrefix) {
                List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
                spec = new ExcC14NParameterSpec(inc);
            } else {
                spec = null;
            }
View Full Code Here

    }
    @SuppressWarnings("unchecked")
    private static Key resolve(SOAPElement securityTokenReference,XMLCryptoContext context, Purpose purpose)throws KeySelectorException {
        try{
            FilterProcessingContext wssContext = (FilterProcessingContext)context.get(MessageConstants.WSS_PROCESSING_CONTEXT);
            SecurableSoapMessage secureMsg = wssContext.getSecurableSoapMessage();
            AlgorithmSuite algSuite = wssContext.getAlgorithmSuite();
            String encAlgo = null;
            boolean isPolicyRecipient = (wssContext.getMode()== FilterProcessingContext.WSDL_POLICY);
            if(algSuite != null){
                encAlgo = algSuite.getEncryptionAlgorithm();
            }
           
            SecurityPolicy securityPolicy = wssContext.getSecurityPolicy();
            boolean isBSP = false;
            if(securityPolicy != null) {
                if (PolicyTypeUtil.messagePolicy(securityPolicy)) {
                    isBSP = ((MessagePolicy)securityPolicy).isBSP();
                } else {
                    isBSP = ((WSSPolicy)securityPolicy).isBSP();
                }
            }
           
            SecurityTokenReference str = new SecurityTokenReference(securityTokenReference, isBSP);
            ReferenceElement refElement = str.getReference();
            HashMap tokenCache = wssContext.getTokenCache();
            HashMap insertedX509Cache = wssContext.getInsertedX509Cache();
            SignaturePolicy policy = (SignaturePolicy)wssContext.getInferredPolicy();
            SignaturePolicy inferredSignaturePolicy = null;
            if(isPolicyRecipient){
                int i = wssContext.getInferredSecurityPolicy().size() - 1;
                //When we call SigProc.verifySignature for a SAMLAssertion from KeyResolver
                if (PolicyTypeUtil.signaturePolicy(wssContext.getInferredSecurityPolicy().get(i))) {
                    inferredSignaturePolicy = (SignaturePolicy)wssContext.getInferredSecurityPolicy().get(i);
                }
            } 
            // will be only during verify.
            AuthenticationTokenPolicy.X509CertificateBinding keyBinding = null;
           
            //TODO: what is this case here
            if(policy != null) {
                keyBinding = (AuthenticationTokenPolicy.X509CertificateBinding) policy.newX509CertificateKeyBinding();
            }
           
            Key returnKey = null;
            boolean isSymmetric = false;
            if (refElement instanceof KeyIdentifier) {
                KeyIdentifier keyId = (KeyIdentifier)refElement;
                if(keyBinding != null){
                    keyBinding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                    keyBinding.setValueType(keyId.getValueType());
                }
               
               
                if (MessageConstants.X509SubjectKeyIdentifier_NS.equals(keyId.getValueType()) ||
                        MessageConstants.X509v3SubjectKeyIdentifier_NS.equals(keyId.getValueType())) {
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                        x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                       
                        if(inferredKB == null){                          
                            inferredSignaturePolicy.setKeyBinding(x509Binding);
                         } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                            if(dktBind.getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                            else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                                dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                                isSymmetric = true;
                            }
                        }

                    }                  
                    if (purpose == Purpose.VERIFY) {
                        byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                        wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                        // add missing update to other party certificate
                        X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                wssContext.getExtraneousProperties(),keyIdBytes);
                        if (!isSymmetric) {
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                    DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                        }
                        returnKey = cert.getPublicKey();
                    } else if(purpose == Purpose.SIGN){
                        returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                wssContext.getExtraneousProperties(),
                                XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                    }
                   
                   
                } else if (MessageConstants.ThumbPrintIdentifier_NS.equals(keyId.getValueType())) {
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setValueType(MessageConstants.ThumbPrintIdentifier_NS);
                        x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                        if(inferredKB == null){
                            inferredSignaturePolicy.setKeyBinding(x509Binding);
                         } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                            if(dktBind.getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                            else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                                dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                                isSymmetric = true;
                            }
                        }

                    }                   
                    if (purpose == Purpose.VERIFY) {
                        byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                        wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                        //update other party subject
                        X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                wssContext.getExtraneousProperties(),keyIdBytes, MessageConstants.THUMB_PRINT_TYPE);
                        if (!isSymmetric) {
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                    DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                        }
                        returnKey = cert.getPublicKey();
                    } else if(purpose == Purpose.SIGN){
                        returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                wssContext.getExtraneousProperties(),
                                XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()), MessageConstants.THUMB_PRINT_TYPE);
                    }
                   
                }else if (MessageConstants.EncryptedKeyIdentifier_NS.equals(keyId.getValueType())){
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                        skBinding.setKeyBinding(x509Binding);
                        //TODO: ReferenceType and ValueType not set on X509Binding
                        if(inferredKB == null){
                            inferredSignaturePolicy.setKeyBinding(skBinding);
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);
                        }
                    }
                    //Set return key here
                    String ekSha1RefValue = (String)wssContext.getExtraneousProperty("EncryptedKeySHA1");
                    Key secretKey = (Key)wssContext.getExtraneousProperty("SecretKey");
                    String keyRefValue = keyId.getReferenceValue();
                    if(ekSha1RefValue != null && secretKey != null){
                        if(ekSha1RefValue.equals(keyRefValue))
                            returnKey = secretKey;
                    }else{
                        String message = "EncryptedKeySHA1 reference not correct";
                        logger.log(Level.SEVERE,LogStringsMessages.WSS_1306_UNSUPPORTED_KEY_IDENTIFIER_REFERENCE_TYPE(), new Object[] {message});
                        throw new KeySelectorException(message);
                    }
                    //returnKey = null;
                } else if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE.equals(keyId.getValueType()) ||
                        MessageConstants.WSSE_SAML_v2_0_KEY_IDENTIFIER_VALUE_TYPE.equals (keyId.getValueType ())) {
                   
                    String assertionID = keyId.getReferenceValue();
                    Element tokenElement = wssContext.getIssuedSAMLToken();
                    if (tokenElement == null) {
                        Assertion samlAssertion = (Assertion)tokenCache.get(assertionID);
                        if (samlAssertion == null) {
                            if (str.getSamlAuthorityBinding() != null) {
                                tokenElement = wssContext.getSecurityEnvironment().
                                        locateSAMLAssertion(
                                        wssContext.getExtraneousProperties(), str.getSamlAuthorityBinding(), assertionID, secureMsg.getSOAPPart());
                            } else {
                                tokenElement = SAMLUtil.locateSamlAssertion(assertionID,secureMsg.getSOAPPart());
                                if (!("true".equals((String)wssContext.getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))) ||
                                        "false".equals((String)wssContext.getExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED))){
                                    wssContext.setExtraneousProperty(MessageConstants.SAML_SIG_RESOLVED,"false");
                                }
                            }
                        } else {
                            try {
                                tokenElement = samlAssertion.toElement(null);
                            } catch (Exception e) {
                                logger.log(Level.SEVERE,LogStringsMessages.WSS_1355_UNABLETO_RESOLVE_SAML_ASSERTION(),e.getMessage());
                                throw new KeySelectorException(e);
                            }
                        }
                   }
                   
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                        if(inferredKB == null){  
                            if (wssContext.hasIssuedToken()){
                                    inferredSignaturePolicy.setKeyBinding(itkBinding);
                            }else{
                                inferredSignaturePolicy.setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
                            }                           
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                             if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);

                        }
                    }

                    returnKey = resolveSamlAssertion(context,tokenElement, purpose, assertionID);
                    addAuthorityId(tokenElement,wssContext);
                    if (wssContext.hasIssuedToken() && returnKey != null){
                        SecurityUtil.initInferredIssuedTokenContext(wssContext, str, returnKey);   
                    }                   

                } else {
                   
                    // it could be SAML AssertionID without ValueType on KeyIdentifier
                    String assertionID = keyId.getDecodedReferenceValue();
                    Element samlAssertion = null;
                    try {
                        samlAssertion = resolveSAMLToken(str, assertionID, wssContext);
                    } catch (Exception e) {
                        if(logger.isLoggable(Level.FINEST)){
                        logger.log(Level.FINEST,"Error occurred while trying " +
                                "to resolve SAML assertion"+e.getMessage());
                        }
                    }
                   
                    if (samlAssertion != null) {
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            IssuedTokenKeyBinding itkBinding = new IssuedTokenKeyBinding();
                            if(inferredKB == null){
                                if (wssContext.hasIssuedToken()){
                                    inferredSignaturePolicy.setKeyBinding(itkBinding);
                                }else{
                                    inferredSignaturePolicy.setKeyBinding(new AuthenticationTokenPolicy.SAMLAssertionBinding());
                                }
                            } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                                if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                    ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(itkBinding);
                            }
                        }                       
                        returnKey = resolveSamlAssertion(context,samlAssertion, purpose, assertionID);
                        addAuthorityId(samlAssertion,wssContext);

                        //whenever we have SAML we want to record the proofkey and str
                        if (wssContext.hasIssuedToken() && returnKey != null){
                            SecurityUtil.initInferredIssuedTokenContext(wssContext, str, returnKey);                       
                        }
                    
                    } else {
                        // now assume its an X509Token
                        // Note: the code below assumes base64 EncodingType for X509 SKI
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                            x509Binding.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
                            x509Binding.setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
                            if(inferredKB == null){                          
                                inferredSignaturePolicy.setKeyBinding(x509Binding);
                            } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                                ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                                DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                                if(dktBind.getOriginalKeyBinding() == null)
                                    ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(x509Binding);
                                else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                                    dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                                }
                            }

                        }                       
                        if (purpose == Purpose.VERIFY) {
                            byte[] keyIdBytes = XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue());
                            wssContext.setExtraneousProperty(MessageConstants.REQUESTER_KEYID, new String(keyIdBytes));
                            //update other party certificate
                            X509Certificate cert = wssContext.getSecurityEnvironment().getCertificate(
                                    wssContext.getExtraneousProperties(),
                                    XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                            wssContext.getSecurityEnvironment().updateOtherPartySubject(
                                DefaultSecurityEnvironmentImpl.getSubject(wssContext), cert);
                            returnKey = cert.getPublicKey();
                           
                        } else if(purpose == Purpose.SIGN){
                            returnKey =wssContext.getSecurityEnvironment().getPrivateKey(
                                    wssContext.getExtraneousProperties(),
                                    XMLUtil.getDecodedBase64EncodedData(keyId.getReferenceValue()));
                        }
                    }

                }
               
            } else if (refElement instanceof DirectReference) {
                if(keyBinding != null){
                    keyBinding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                   
                }
                String uri = ((DirectReference) refElement).getURI();
                if (isBSP && !uri.startsWith("#")) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1356_VIOLATION_BSP_R_5204());
                    throw new XWSSecurityException("Violation of BSP R5204 "
                            + ": When a SECURITY_TOKEN_REFERENCE uses a Direct Reference to an INTERNAL_SECURITY_TOKEN, it MUST use a Shorthand XPointer Reference");
                }
               
                String valueType = ((DirectReference) refElement).getValueType();
                if (MessageConstants.DKT_VALUETYPE.equals(valueType) ||
                        MessageConstants.DKT_13_VALUETYPE.equals(valueType)){
                    //TODO: this will work for now but need to handle this case here later
                    valueType = null;
                }

                if (MessageConstants.X509v3_NS.equals(valueType)||MessageConstants.X509v1_NS.equals(valueType)) {
                    // its an X509 Token
                    if(keyBinding != null){
                        keyBinding.setValueType(valueType);
                    }
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    X509SecurityToken token = (X509SecurityToken) insertedX509Cache.get(wsuId);              
                    //if(token == null)
                    //    token =(X509SecurityToken) tokenCache.get(wsuId);
                   
                    if(token == null){
                        token = (X509SecurityToken)resolveToken(wsuId,context);
                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1357_UNABLETO_LOCATE_TOKEN());
                            throw new KeySelectorException("Token with Id "+wsuId+ "not found");
                        }else{
                            tokenCache.put(wsuId, token);
                        }
                    }
                   
                    if(isPolicyRecipient && inferredSignaturePolicy != null){
                        MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                        AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                        x509Binding.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
                        x509Binding.setValueType(valueType);
                        if(inferredKB == null){ 
                            inferredSignaturePolicy.setKeyBinding(x509Binding);
                        } else if(PolicyTypeUtil.symmetricKeyBinding(inferredKB)){
                            ((SymmetricKeyBinding)inferredKB).setKeyBinding(x509Binding);
                            isSymmetric = true;
                        } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                            DerivedTokenKeyBinding dktBind = (DerivedTokenKeyBinding)inferredKB;
                            if(dktBind.getOriginalKeyBinding() == null)
                                dktBind.setOriginalKeyBinding(x509Binding);
                            else if(PolicyTypeUtil.symmetricKeyBinding(dktBind.getOriginalKeyBinding())){
                                dktBind.getOriginalKeyBinding().setKeyBinding(x509Binding);
                                isSymmetric = true;
                            }
                        }

                    }
                   
                    returnKey = resolveX509Token(wssContext,  token, purpose, isSymmetric);
                   
                } else if(MessageConstants.EncryptedKey_NS.equals(valueType)) {
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    SecurityToken token = (SecurityToken)tokenCache.get(wsuId);
                    if(token == null){
                        token = resolveToken(wsuId, context);
                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1357_UNABLETO_LOCATE_TOKEN());
                            throw new KeySelectorException("Token with Id "+wsuId+ "not found");//TODO LOG ::Venu
                        }else{
                            tokenCache.put(wsuId, token);
                        }
                    }
                        KeyInfoHeaderBlock kiHB = ((EncryptedKeyToken)token).getKeyInfo();
                        SecurityTokenReference sectr = kiHB.getSecurityTokenReference(0);
                        SOAPElement se = sectr.getAsSoapElement();
                        ReferenceElement refElem = sectr.getReference();
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            SymmetricKeyBinding skBinding = new SymmetricKeyBinding();
                            AuthenticationTokenPolicy.X509CertificateBinding x509Binding = new AuthenticationTokenPolicy.X509CertificateBinding();
                            skBinding.setKeyBinding(x509Binding);
                            //TODO: ReferenceType and ValueType not set on X509Binding
                            if(inferredKB == null){
                                inferredSignaturePolicy.setKeyBinding(skBinding);
                            } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                                if(((DerivedTokenKeyBinding)inferredKB).getOriginalKeyBinding() == null)
                                    ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(skBinding);

                            }
                        }
                       
                        Key privKey  = resolve(se, context, Purpose.SIGN);
                        Element cipherData = (Element)((EncryptedKeyToken)token).getAsSoapElement().getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                        String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                        byte[] decodedCipher = Base64.decode(cipherValue);
                        byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                           
                        String encEkSha1 = Base64.encode(ekSha1);
                        wssContext.setExtraneousProperty(MessageConstants.EK_SHA1_VALUE, encEkSha1);

                        returnKey = ((EncryptedKeyToken)token).getSecretKey(privKey, encAlgo);    
                        wssContext.setExtraneousProperty(MessageConstants.SECRET_KEY_VALUE, returnKey);
                } else if (MessageConstants.SCT_VALUETYPE.equals(valueType) || MessageConstants.SCT_13_VALUETYPE.equals(valueType)) {
                    // could be wsuId or SCT Session Id
                    String sctId = secureMsg.getIdFromFragmentRef(uri);
                    SecurityToken token = (SecurityToken)tokenCache.get(sctId);
                   
                    if(token == null){
                        token = SecurityUtil.locateBySCTId(wssContext, uri);
                        if (token == null) {
                            token = resolveToken(sctId, context);
                        }

                        if(token == null){
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1358_UNABLETO_LOCATE_SCT_TOKEN());
                            throw new KeySelectorException("SCT Token with Id "+sctId+ "not found");
                        }else{
                            tokenCache.put(sctId, token);
                        }
                    }

                    if (token instanceof SecurityContextToken) {
                        //handling for SecurityContext Token
                        if(isPolicyRecipient && inferredSignaturePolicy != null){
                            MLSPolicy inferredKB = inferredSignaturePolicy.getKeyBinding();
                            SecureConversationTokenKeyBinding sctBinding = new SecureConversationTokenKeyBinding();
                            if(inferredKB == null){
                                inferredSignaturePolicy.setKeyBinding(sctBinding);
                            } else if(PolicyTypeUtil.derivedTokenKeyBinding(inferredKB)){
                                ((DerivedTokenKeyBinding)inferredKB).setOriginalKeyBinding(sctBinding);
                            }
                        }                      
                        returnKey = resolveSCT(wssContext, (SecurityContextTokenImpl)token, purpose);
                       
                    } else {
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1359_INVALID_VALUETYPE_NON_SC_TTOKEN());
                        throw new KeySelectorException("Incorrect ValueType: " + MessageConstants.SCT_VALUETYPE + ", specified for a Non SCT Token");
                    }

                } else if (null == valueType) {
                    // Log fails BSP:R3059 and R3058
                    //logger.log(Level.WARNING, "Fails BSP requirements R3058 and 3059");
                   
                    // Do default processing
                    String wsuId = secureMsg.getIdFromFragmentRef(uri);
                    SecurityToken token = (SecurityToken)tokenCache.get(wsuId);
                   
                    if(token == null){
                        token = resolveToken(wsuId, context);
                        if (token == null) {
View Full Code Here

    }
    @SuppressWarnings("unchecked")
    public static void encrypt(FilterProcessingContext context) throws XWSSecurityException{
       
        //TODO: support for QName and XPath
        SecurableSoapMessage secureMsg = context.getSecurableSoapMessage();
        SecurityHeader _secHeader = secureMsg.findOrCreateSecurityHeader();
       
        boolean _exportCertificate = false;
        SecretKey _symmetricKey = null;
        SecretKey  keyEncSK = null;
       
        X509Certificate _x509Cert = null;
        Key samlkey = null;
        KeyInfoStrategy keyInfoStrategy =  null;
       
        String referenceType = null;
        String x509TokenId = null;
        String keyEncAlgo = XMLCipher.RSA_v1dot5;
        String dataEncAlgo = MessageConstants.TRIPLE_DES_BLOCK_ENCRYPTION;
        String symmetricKeyName = null;
       
        AuthenticationTokenPolicy.X509CertificateBinding certificateBinding = null;
       
        WSSPolicy wssPolicy = (WSSPolicy)context.getSecurityPolicy();
        EncryptionPolicy.FeatureBinding featureBinding =(EncryptionPolicy.FeatureBindingwssPolicy.getFeatureBinding();
        WSSPolicy keyBinding = (WSSPolicy)wssPolicy.getKeyBinding();
       
        AlgorithmSuite algSuite = context.getAlgorithmSuite();
       
        SecurityTokenReference samlTokenRef = null;
        SecurityTokenReference secConvRef = null;
        SecurityTokenReference ekTokenRef = null;
        SecurityTokenReference dktSctTokenRef = null;
        SecurityTokenReference issuedTokenRef = null;
        //adding EncryptedKey Direct Reference to handle EncryptBeforeSigning
        SecurityTokenReference ekDirectRef = null;
       
        DerivedKeyTokenHeaderBlock dktHeadrBlock = null;
       
        SecurityContextTokenImpl sct = null;
        boolean sctTokenInserted = false;
        SOAPElement sctElement = null;
        boolean sctWithDKT = false;
        boolean includeSCT = true;
       
        boolean issuedWithDKT = false;
        SecurityTokenReference dktIssuedTokenRef = null;
        SOAPElement issuedTokenElement =  null;
        Element issuedTokenElementFromMsg =  null;
        boolean issuedTokenInserted = false;
        boolean includeIST = true;
       
        boolean dktSender = false;
       
        //Key obtained from SymmetricKeyBinding in case of DKT
        Key originalKey = null;
        String ekId = context.getSecurableSoapMessage().generateId();
        String insertedEkId = null;
        //Check to see if same x509 token used for Signature and Encryption
        boolean skbX509TokenInserted = false;
       
        boolean useStandaloneRefList = false;
       
        HashMap ekCache = context.getEncryptedKeyCache();
       
        SOAPElement x509TokenElement = null;
       
        SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
       
        if(log.isLoggable(Level.FINEST)){
            log.log(Level.FINEST, "KeyBinding in Encryption is "+keyBinding);
        }
       
        boolean wss11Receiver = "true".equals(context.getExtraneousProperty("EnableWSS11PolicyReceiver"));
        boolean wss11Sender = "true".equals(context.getExtraneousProperty("EnableWSS11PolicySender"));
        boolean sendEKSHA1 =  wss11Receiver && wss11Sender && (getEKSHA1Ref(context) != null);
        boolean wss10 = !wss11Sender;
       
        String tmp = featureBinding.getDataEncryptionAlgorithm();
        if (tmp == null || "".equals(tmp)) {
            if (context.getAlgorithmSuite() != null) {
                tmp = context.getAlgorithmSuite().getEncryptionAlgorithm();
            } else {
                // warn that no dataEncAlgo was set
            }
        }
        //TODO :: Change to getDataEncryptionAlgorith,
        if(tmp != null && !"".equals(tmp)){
            dataEncAlgo = tmp;
        }
       
        if (context.getAlgorithmSuite() != null) {
            keyEncAlgo = context.getAlgorithmSuite().getAsymmetricKeyAlgorithm();
        }
       
        // derivedTokenKeyBinding with x509 as originalkeyBinding is to be treated same as
        // DerivedKey with Symmetric binding and X509 as key binding of Symmetric binding
        if(PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)){
            DerivedTokenKeyBinding dtk = (DerivedTokenKeyBinding)keyBinding.clone();
            WSSPolicy originalKeyBinding = dtk.getOriginalKeyBinding();
           
            if (PolicyTypeUtil.x509CertificateBinding(originalKeyBinding)){
                AuthenticationTokenPolicy.X509CertificateBinding ckBindingClone =
                        (AuthenticationTokenPolicy.X509CertificateBinding)originalKeyBinding.clone();
                //create a symmetric key binding and set it as original key binding of dkt
                SymmetricKeyBinding skb = new SymmetricKeyBinding();
                skb.setKeyBinding(ckBindingClone);
                // set the x509 binding as key binding of symmetric binding
                dtk.setOriginalKeyBinding(skb);
                keyBinding = dtk;
            }
        }
       
        if (PolicyTypeUtil.usernameTokenPolicy(keyBinding)) {
            log.log(Level.SEVERE,"WSS1210.unsupported.UsernameToken.AsKeyBinding.EncryptionPolicy");
            throw new XWSSecurityException("UsernameToken as KeyBinding for EncryptionPolicy is Not Yet Supported");
        } else if(PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
            //we need to use standalone reflist to support EncryptBeforeSigning
            useStandaloneRefList=true;
            if ( context.getX509CertificateBinding() != null) {
                certificateBinding  = context.getX509CertificateBinding();
                context.setX509CertificateBinding(null);
            } else {
                certificateBinding  =(AuthenticationTokenPolicy.X509CertificateBinding)keyBinding;
            }
           
            x509TokenId = certificateBinding.getUUID();
            if(x509TokenId == null || x509TokenId.equals("")){
                x509TokenId = secureMsg.generateId();
            }
            if(log.isLoggable(Level.FINEST)){
                log.log(Level.FINEST, "Certificate was "+_x509Cert);
                log.log(Level.FINEST, "BinaryToken ID "+x509TokenId);
            }
           
            HashMap tokenCache = context.getTokenCache();
            HashMap insertedX509Cache = context.getInsertedX509Cache();
           
            SecurityUtil.checkIncludeTokenPolicy(context, certificateBinding, x509TokenId);
           
            _x509Cert = certificateBinding.getX509Certificate();
            referenceType = certificateBinding.getReferenceType();
            if(referenceType.equals("Identifier") && certificateBinding.getValueType().equals(MessageConstants.X509v1_NS)){
                log.log(Level.SEVERE,"WSS1211.unsupported.KeyIdentifierStrategy.X509v1");
                throw new XWSSecurityException("Key Identifier strategy with X509v1 certificate is not allowed");
            }
            keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
            _exportCertificate = true;
            keyInfoStrategy.setCertificate(_x509Cert);
           
            if(MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType)){
               
                X509SecurityToken token = (X509SecurityToken)tokenCache.get(x509TokenId);
                if(token == null){
                    String valueType = certificateBinding.getValueType();
                    if(valueType==null||valueType.equals("")){
                        //default valueType for X509 as v3
                        valueType = MessageConstants.X509v3_NS;
                    }
                    token = new X509SecurityToken(secureMsg.getSOAPPart(),_x509Cert,x509TokenId, valueType);
                }
                if(insertedX509Cache.get(x509TokenId) == null){
                    secureMsg.findOrCreateSecurityHeader().insertHeaderBlock(token);
                    insertedX509Cache.put(x509TokenId, token);
                    x509TokenElement = secureMsg.findOrCreateSecurityHeader().getNextSiblingOfTimestamp();
                } else{
                    x509TokenElement = secureMsg.getElementByWsuId(x509TokenId);
                }
               
                //x509TokenElement = secureMsg.findOrCreateSecurityHeader().getFirstChildElement();
               
            }
           
            //TODO:Revisit this -Venu
            tmp = null;
            tmp = certificateBinding.getKeyAlgorithm();
            if(tmp != null && !tmp.equals("")){
                keyEncAlgo = tmp;
            }
            _symmetricKey = SecurityUtil.generateSymmetricKey(dataEncAlgo);
        } else if (PolicyTypeUtil.symmetricKeyBinding(keyBinding)) {
            SymmetricKeyBinding skb = null;
            if ( context.getSymmetricKeyBinding() != null) {
                skb = context.getSymmetricKeyBinding();
                context.setSymmetricKeyBinding(null);
            } else {
                skb = (SymmetricKeyBinding)keyBinding;
            }
           
            KeyInfoHeaderBlock keyInfoBlock  = null;
           
            if(!skb.getKeyIdentifier().equals(MessageConstants._EMPTY)){
                keyEncAlgo = skb.getKeyAlgorithm();
                if(keyEncAlgo != null && !"".equals(keyEncAlgo)){
                    _symmetricKey = SecurityUtil.generateSymmetricKey(dataEncAlgo);
                }
                keyInfoStrategy = KeyInfoStrategy.getInstance(MessageConstants.KEY_NAME_TYPE);
                keyEncSK = skb.getSecretKey();
                symmetricKeyName = skb.getKeyIdentifier();
                String secKeyAlgo = keyEncSK.getAlgorithm();
               
                if(_symmetricKey == null){
                    ((KeyNameStrategy)keyInfoStrategy).setKeyName(symmetricKeyName);
                    _symmetricKey = keyEncSK;
                    keyEncSK = null;
                }
            } else if (sendEKSHA1) {
                //get the signing key and EKSHA1 reference from the Subject, it was stored from the incoming message
                String ekSha1Ref = getEKSHA1Ref(context);
                _symmetricKey = skb.getSecretKey();
               
                keyInfoBlock = new KeyInfoHeaderBlock(secureMessage.getSOAPPart());
                ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                EncryptedKeySHA1Identifier refElem = new EncryptedKeySHA1Identifier(secureMessage.getSOAPPart());
                refElem.setReferenceValue(ekSha1Ref);
                ekTokenRef.setReference(refElem);
                //set the wsse11:TokenType attribute as required by WSS 1.1
                //ekTokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
               
                referenceType = MessageConstants.EK_SHA1_TYPE;
                keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
                //keyInfoStrategy.insertKey(ekTokenRef, secureMsg);
               
                //TODO: the below cond is always true.
            } else if (wss11Sender || wss10) {
                _symmetricKey = skb.getSecretKey();
                useStandaloneRefList = true;
               
                if(!skb.getCertAlias().equals(MessageConstants._EMPTY)){
                    certificateBinding = new AuthenticationTokenPolicy.X509CertificateBinding();
                    //x509Binding.newPrivateKeyBinding();
                    certificateBinding.setCertificateIdentifier(skb.getCertAlias());
                    _x509Cert = context.getSecurityEnvironment().getCertificate(context.getExtraneousProperties(), certificateBinding.getCertificateIdentifier(), false);
                    certificateBinding.setX509Certificate(_x509Cert);
                    certificateBinding.setReferenceType("Direct");
                }else if ( context.getX509CertificateBinding() != null ) {
                    certificateBinding = context.getX509CertificateBinding();
                    context.setX509CertificateBinding(null);
                }
               
                _x509Cert = certificateBinding.getX509Certificate();
                x509TokenId = certificateBinding.getUUID();
                if(x509TokenId == null || x509TokenId.equals("")){
                    x509TokenId = secureMsg.generateId();
                }
               
                if(log.isLoggable(Level.FINEST)){
                    log.log(Level.FINEST, "Certificate was "+_x509Cert);
                    log.log(Level.FINEST, "BinaryToken ID "+x509TokenId);
                }
               
                HashMap tokenCache = context.getTokenCache();
                HashMap insertedX509Cache = context.getInsertedX509Cache();
               
                SecurityUtil.checkIncludeTokenPolicy(context, certificateBinding, x509TokenId);
               
                X509SecurityToken token = (X509SecurityToken)tokenCache.get(x509TokenId);
                if(token == null){
                    String valueType = certificateBinding.getValueType();
                    if(valueType==null||valueType.equals("")){
                        //default valueType for X509 as v3
                        valueType = MessageConstants.X509v3_NS;
                    }
                    token = new X509SecurityToken(secureMsg.getSOAPPart(),_x509Cert,x509TokenId, valueType);
                    tokenCache.put(x509TokenId, token);
                    context.setCurrentSecret(_symmetricKey);
                } else{
                    skbX509TokenInserted = true;
                    _symmetricKey = context.getCurrentSecret();
                   
                }
                ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                DirectReference reference = new DirectReference();
                insertedEkId = (String)ekCache.get(x509TokenId);
                if(insertedEkId == null)
                    insertedEkId = ekId;
                reference.setURI("#"+insertedEkId);
                reference.setValueType(MessageConstants.EncryptedKey_NS);
                ekTokenRef.setReference(reference);
               
                if(!skbX509TokenInserted){
                   
                    referenceType =  certificateBinding.getReferenceType();
                    if(referenceType.equals("Identifier") && certificateBinding.getValueType().equals(MessageConstants.X509v1_NS)){
                        log.log(Level.SEVERE,"WSS1211.unsupported.KeyIdentifierStrategy.X509v1");
                        throw new XWSSecurityException("Key Identifier strategy with X509v1 is not allowed");
                    }
                    keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
                    _exportCertificate = true;
                    keyInfoStrategy.setCertificate(_x509Cert);
                    //Store SymmetricKey generated in ProcessingContext
                    context.setExtraneousProperty("SecretKey", _symmetricKey);
                }
                if(MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType)){
                    if(insertedX509Cache.get(x509TokenId) == null){
                        secureMsg.findOrCreateSecurityHeader().insertHeaderBlock(token);
                        insertedX509Cache.put(x509TokenId, token);
                        x509TokenElement = secureMsg.findOrCreateSecurityHeader().getNextSiblingOfTimestamp();
                    } else{
                        //x509TokenElement = secureMsg.findOrCreateSecurityHeader().getFirstChildElement();
                        x509TokenElement = secureMsg.getElementByWsuId(x509TokenId);
                    }
                }
               
            }
           
        } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
            //TODO handler saml, it should be a remote SAML Assertion
            // since a message from the sender cannot have the receivers assertion as part of message
            AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding =
                    (AuthenticationTokenPolicy.SAMLAssertionBinding)keyBinding;
           
            Assertion assertion1 = null;
            Assertion assertion2 = null;
           
            try {
                if (System.getProperty("com.sun.xml.wss.saml.binding.jaxb") == null ) {
                    if (samlBinding.getAssertion().getAttributeNode("ID") != null) {
                        assertion1 = (Assertion)com.sun.xml.wss.saml.assertion.saml20.jaxb20.Assertion.fromElement(samlBinding.getAssertion());
                    }else{
                        assertion1 = (Assertion)com.sun.xml.wss.saml.assertion.saml11.jaxb20.Assertion.fromElement(samlBinding.getAssertion());
                    }
                } else {
                    assertion2 = (Assertion)com.sun.xml.wss.saml.assertion.saml11.jaxb10.Assertion.fromElement(samlBinding.getAssertion());
                }
            } catch (SAMLException ex) {
                log.log(Level.SEVERE, "WSS1212.error.SAMLAssertionException");
                throw new XWSSecurityException(ex);
            }
           
            String assertionID = null;
            if (assertion1 != null) {
                HashMap tokenCache = context.getTokenCache();
                //assuming unique IDs
                assertionID = ((com.sun.xml.wss.saml.Assertion)assertion1).getAssertionID();
                tokenCache.put(assertionID, assertion1);
            } else if (assertion2 != null) {
                HashMap tokenCache = context.getTokenCache();
                //assuming unique IDs
                assertionID = ((com.sun.xml.wss.saml.Assertion)assertion2).getAssertionID();
                tokenCache.put(assertionID, assertion2);
            } else{
                log.log(Level.SEVERE,"WSS1213.null.SAMLAssertion");
                throw new XWSSecurityException("SAML Assertion is NULL");
            }
           
            //Key key = null;
            samlkey = KeyResolver.resolveSamlAssertion(
                    context.getSecurableSoapMessage(), samlBinding.getAssertion(), true, context, assertionID);
           
            /*
            _x509Cert = context.getSecurityEnvironment().getCertificate(
                    context.getExtraneousProperties() ,(PublicKey)key, false);
            if (_x509Cert == null) {
                log.log(Level.SEVERE,"WSS1214.unableto.locate.certificate.SAMLAssertion");
                throw new XWSSecurityException("Could not locate Certificate corresponding to Key in SubjectConfirmation of SAML Assertion");
            }*/
           
            if (!"".equals(samlBinding.getKeyAlgorithm())) {
                keyEncAlgo = samlBinding.getKeyAlgorithm();
            }
           
            _symmetricKey = SecurityUtil.generateSymmetricKey(dataEncAlgo);
           
            referenceType = samlBinding.getReferenceType();
            if (referenceType.equals(MessageConstants.EMBEDDED_REFERENCE_TYPE)) {
                log.log(Level.SEVERE, "WSS1215.unsupported.EmbeddedReference.SAMLAssertion");
                throw new XWSSecurityException("Embedded Reference Type for SAML Assertions not supported yet");
            }
           
            String assertionId = null;
            if ( assertion1 != null) {
                assertionId = ((com.sun.xml.wss.saml.Assertion)assertion1).getAssertionID();
            }else if ( assertion2 != null) {
                assertionId = ((com.sun.xml.wss.saml.Assertion)assertion2).getAssertionID();
            }
            Element binding = samlBinding.getAuthorityBinding();
            samlTokenRef = new SecurityTokenReference(secureMsg.getSOAPPart());
            String strId = samlBinding.getSTRID();
            if(strId == null){
                strId = secureMsg.generateId();
            }
            samlTokenRef.setWsuId(strId);
           
            if (binding != null) {
                samlTokenRef.setSamlAuthorityBinding(binding, secureMsg.getSOAPPart());
            }
            keyInfoStrategy = new KeyIdentifierStrategy(assertionId);
            keyInfoStrategy.insertKey(samlTokenRef, secureMsg);
           
        } else if ( PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
           
            IssuedTokenContext trustContext =  context.getTrustContext();
           
            //get the symmetric key for encryption
            try{
                _symmetricKey = new SecretKeySpec(trustContext.getProofKey(), SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
            } catch(Exception e){
                log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                throw new XWSSecurityException(e);
            }
           
            //Get the IssuedToken and insert it into the message
            GenericToken issuedToken = (GenericToken)trustContext.getSecurityToken();
           
            // check if the token is already present
            IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)keyBinding;
            //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
            String ikbPolicyId = ikb.getUUID();
           
            //Look for TrustToken in TokenCache
            HashMap tokCache = context.getTokenCache();
            Object tok = tokCache.get(ikbPolicyId);
           
            SecurityTokenReference str = null;
            Element strElem = null;
            String tokenVersion = ikb.getIncludeToken();
            includeIST = (IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_VER2.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(tokenVersion)
                          );
           
            if (includeIST && (issuedToken == null)) {
                log.log(Level.SEVERE, "WSS1217.null.IssueToken");
                throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
            }
           
            //trust token to be inserted into message
            if (issuedToken != null) {
                // treat the token as an Opaque entity and just insert the token into message
                Element elem = (Element)issuedToken.getTokenValue();
                //TODO: remove these expensive conversions DOM Imports
                if (tok == null) {
                    issuedTokenElement = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                    //Temp FIX for Issue#26: We need an Id to cache and MS not sending Id in some cases
                    String tokId = issuedTokenElement.getAttribute("Id");
                    if ("".equals(tokId) &&
                            MessageConstants.ENCRYPTED_DATA_LNAME.equals(issuedTokenElement.getLocalName())) {
                        issuedTokenElement.setAttribute("Id", secureMessage.generateId());
                    }
                    tokCache.put(ikbPolicyId, issuedTokenElement);
                } else {
                    issuedTokenInserted = true;
                    // it will be SOAPElement retrieve its wsuId attr
                    String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                    issuedTokenElementFromMsg = secureMessage.getElementById(wsuId);
                    if (issuedTokenElementFromMsg == null) {
                        log.log(Level.SEVERE, "WSS1218.unableto.locate.IssueToken.Message");
                        throw new XWSSecurityException("Could not locate Issued Token in Message");
                    }
                }
            }
           
            if (includeIST) {
                if (trustContext.getAttachedSecurityTokenReference() != null) {
                    strElem = SecurityUtil.convertSTRToElement(trustContext.getAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    log.log(Level.SEVERE, "WSS1219.unableto.refer.Attached.IssueToken");
                    throw new XWSSecurityException("Cannot determine how to reference the Attached Issued Token in the Message");
                }
            } else {
                //Trust Issued Token should not be in message at all, so use an external reference
                if (trustContext.getUnAttachedSecurityTokenReference() != null) {
                    strElem = SecurityUtil.convertSTRToElement(trustContext.getUnAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    log.log(Level.SEVERE, "WSS1220.unableto.refer.Un-Attached.IssueToken");
                    throw new XWSSecurityException("Cannot determine how to reference the Un-Attached Issued Token in the Message");
                }
            }
           
            //TODO: remove these expensive conversions
            Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
            issuedTokenRef = new SecurityTokenReference(XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), imported), false);
            SecurityUtil.updateSamlVsKeyCache(issuedTokenRef, context, _symmetricKey);
           
        } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
           
            SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)keyBinding;
           
            //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
            String sctPolicyId = sctBinding.getUUID();
            //Look for SCT in TokenCache
            HashMap tokCache = context.getTokenCache();
            sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
           
            IssuedTokenContext ictx = context.getSecureConversationContext();
           
            if (sct == null) {
                SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
                if (sct1 == null) {
                    log.log(Level.SEVERE,"WSS1221.null.SecureConversationToken");
                    throw new XWSSecurityException("SecureConversation Token not Found");
                }
               
                sct = new SecurityContextTokenImpl(
                        secureMessage.getSOAPPart(), sct1.getIdentifier().toString(), sct1.getInstance(), sct1.getWsuId(), sct1.getExtElements());
                // put back in token cache
                tokCache.put(sctPolicyId, sct);
            } else {
                sctTokenInserted = true;
                // record the element
                sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
            }
           
            String sctWsuId = sct.getWsuId();
            if (sctWsuId == null) {
                sct.setId(secureMessage.generateId());
            }
            sctWsuId = sct.getWsuId();
           
            secConvRef = new SecurityTokenReference(secureMessage.getSOAPPart());
            DirectReference reference = new DirectReference();
            if (SecureConversationTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(sctBinding.getIncludeToken()) ||
                    SecureConversationTokenKeyBinding.INCLUDE_ALWAYS.equals(sctBinding.getIncludeToken())) {
               
                reference.setURI("#" + sctWsuId);
            } else {
                includeSCT = false;
                reference.setSCTURI(sct.getIdentifier().toString(), sct.getInstance());
            }
           
            secConvRef.setReference(reference);
            referenceType = MessageConstants.DIRECT_REFERENCE_TYPE;
            keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
           
            String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo);
            _symmetricKey = new SecretKeySpec(ictx.getProofKey(), jceAlgo);
           
           
        } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)){
            DerivedTokenKeyBinding dtk = (DerivedTokenKeyBinding)keyBinding.clone();
            WSSPolicy originalKeyBinding = dtk.getOriginalKeyBinding();
           
            String algorithm = null;
            if(algSuite != null){
                algorithm = algSuite.getEncryptionAlgorithm();
            }
            //The offset and length to be used for DKT
            long offset = 0; // Default 0
            long length = SecurityUtil.getLengthFromAlgorithm(algorithm);
           
            if (PolicyTypeUtil.x509CertificateBinding(originalKeyBinding)) {
                //throw new XWSSecurityException("Asymmetric Binding with DerivedKeys under X509Token Policy Not Yet Supported");
            } else if ( PolicyTypeUtil.symmetricKeyBinding(originalKeyBinding)) {
                SymmetricKeyBinding skb = null;
                if ( context.getSymmetricKeyBinding() != null) {
                    skb = context.getSymmetricKeyBinding();
                    context.setSymmetricKeyBinding(null);
                } else{
                    skb = (SymmetricKeyBinding)originalKeyBinding;
                }
               
                if(sendEKSHA1){
                    String ekSha1Ref = getEKSHA1Ref(context);
                    //Construct a derivedKeyToken to be used
                    originalKey = skb.getSecretKey();
                    byte[] secret = originalKey.getEncoded();
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                    String dktId = secureMessage.generateId();
                    String nonce = Base64.encode(dkt.getNonce());
                    //get the symmetric key for encryption key from derivedkeyToken
                    try{
                        String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(algorithm);
                        _symmetricKey = dkt.generateSymmetricKey(jceAlgo);
                    } catch(Exception e){
                        log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                        throw new XWSSecurityException(e);
                    }
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    EncryptedKeySHA1Identifier refElem = new EncryptedKeySHA1Identifier(secureMessage.getSOAPPart());
                    refElem.setReferenceValue(ekSha1Ref);
                    tokenRef.setReference(refElem);
                   
                    //set the wsse11:TokenType attribute as required by WSS 1.1
                    //TODO: uncomment this once MS is ready to accpet this
                    //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                   
                    dktHeadrBlock =
                            new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                   
                    //Construct the STR for Encryption
                    DirectReference reference = new DirectReference();
                    reference.setURI("#"+dktId);
                    ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    ekTokenRef.setReference(reference);
                } else if(wss11Sender || wss10){
                    dktSender = true;
                    originalKey = skb.getSecretKey();
                    if ( context.getX509CertificateBinding() != null ) {
                        certificateBinding = context.getX509CertificateBinding();
                        context.setX509CertificateBinding(null);
                        _x509Cert = certificateBinding.getX509Certificate();
                    }
                    _x509Cert = certificateBinding.getX509Certificate();
                    referenceType =  certificateBinding.getReferenceType();
                    keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
                    _exportCertificate = true;
                    keyInfoStrategy.setCertificate(_x509Cert);
                    x509TokenId = certificateBinding.getUUID();
                    if(x509TokenId == null || x509TokenId.equals("")){
                        x509TokenId = secureMsg.generateId();
                    }
                   
                    if(log.isLoggable(Level.FINEST)){
                        log.log(Level.FINEST, "Certificate was "+_x509Cert);
                        log.log(Level.FINEST, "BinaryToken ID "+x509TokenId);
                    }
                   
                   
                    HashMap tokenCache = context.getTokenCache();
                    HashMap insertedX509Cache = context.getInsertedX509Cache();
                   
                    SecurityUtil.checkIncludeTokenPolicy(context, certificateBinding, x509TokenId);
                   
                    // ReferenceType adjustment in checkIncludeTokenPolicy is also currently
                    // causing an insertion of the X509 into the Message
                    X509SecurityToken insertedx509 =
                            (X509SecurityToken)context.getInsertedX509Cache().get(x509TokenId);
                   
                    // this one is used to determine if the whole BST + EK + DKT(opt)
                    // has been inserted by another filter such as Encryption running before
                    X509SecurityToken token = (X509SecurityToken)tokenCache.get(x509TokenId);
                    if(token == null){
                        if (insertedx509 != null) {
                            token = insertedx509;
                            tokenCache.put(x509TokenId, insertedx509);
                        } else {
                            String valueType = certificateBinding.getValueType();
                            if(valueType==null||valueType.equals("")){
                                //default valueType for X509 as v3
                                valueType = MessageConstants.X509v3_NS;
                            }
                            token = new X509SecurityToken(secureMsg.getSOAPPart(),_x509Cert,x509TokenId, valueType);
                            tokenCache.put(x509TokenId, token);
                        }
                        context.setCurrentSecret(originalKey);
                        //Store SymmetricKey generated in ProcessingContext
                        context.setExtraneousProperty("SecretKey", originalKey);
                    } else{
                        skbX509TokenInserted = true;
                        originalKey = context.getCurrentSecret();
                    }
                    //
                    if(insertedx509 == null){
                        if(MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType)){
                            secureMsg.findOrCreateSecurityHeader().insertHeaderBlock(token);
                            insertedX509Cache.put(x509TokenId, token);
                            x509TokenElement = secureMsg.findOrCreateSecurityHeader().getNextSiblingOfTimestamp();
                        }
                    } else{
                        //x509TokenElement = secureMsg.getElementByWsuId(x509TokenId);
                        x509TokenElement = insertedx509;
                    }
                    //}
                   
                    //Construct a derivedKeyToken to be used
                    byte[] secret = originalKey.getEncoded();
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                    String dktId = secureMessage.generateId();
                    String nonce = Base64.encode(dkt.getNonce());
                    //get the symmetric key for encryption key from derivedkeyToken
                    try{
                        String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(algorithm);
                        _symmetricKey = dkt.generateSymmetricKey(jceAlgo);
                    } catch(Exception e){
                        log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                        throw new XWSSecurityException(e);
                    }
                   
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    DirectReference reference = new DirectReference();
                    //TODO: PLUGFEST Commeting for now as Microsoft setting the EncryptedKey type on reference valueType
                    //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                    //set id of encrypted key in STR of DKT
                    insertedEkId = (String)ekCache.get(x509TokenId);
                    if(insertedEkId == null)
                        insertedEkId = ekId;
                    reference.setURI("#"+insertedEkId);
                    reference.setValueType(MessageConstants.EncryptedKey_NS);
                    tokenRef.setReference(reference);
                    dktHeadrBlock =
                            new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength(), dktId);
                   
                    //Construct the STR for Encryption
                    DirectReference refEnc = new DirectReference();
                    refEnc.setURI("#"+dktId);
                    ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    ekTokenRef.setReference(refEnc);
                }
            } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(originalKeyBinding)) {
               
                sctWithDKT = true;
               
                SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)originalKeyBinding;
                //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
                String sctPolicyId = sctBinding.getUUID();
                //Look for SCT in TokenCache
                HashMap tokCache = context.getTokenCache();
                sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
               
                IssuedTokenContext ictx = context.getSecureConversationContext();
               
                if (sct == null) {
                    SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
                    if (sct1 == null) {
                        log.log(Level.SEVERE, "WSS1221.null.SecureConversationToken");
                        throw new XWSSecurityException("SecureConversation Token not Found");
                    }
                   
                    sct = new SecurityContextTokenImpl(
                            secureMessage.getSOAPPart(), sct1.getIdentifier().toString(), sct1.getInstance(), sct1.getWsuId(), sct1.getExtElements());
                    // put back in token cache
                    tokCache.put(sctPolicyId, sct);
                } else {
                    sctTokenInserted = true;
                    // record the element
                    sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
                }
               
                String sctWsuId = sct.getWsuId();
                if (sctWsuId == null) {
                    sct.setId(secureMessage.generateId());
                }
                sctWsuId = sct.getWsuId();
               
                byte[] secret =  context.getSecureConversationContext().getProofKey();
                DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                String dktId = secureMessage.generateId();
                String nonce = Base64.encode(dkt.getNonce());
                //get the symmetric key for encryption key from derivedkeyToken
                try{
                    _symmetricKey = dkt.generateSymmetricKey(SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
                //STR for DerivedKeyToken
                SecurityTokenReference secRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                DirectReference reference = new DirectReference();
                if (SecureConversationTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(sctBinding.getIncludeToken()) ||
                        SecureConversationTokenKeyBinding.INCLUDE_ALWAYS.equals(sctBinding.getIncludeToken())) {
                   
                    reference.setURI("#" + sctWsuId);
                } else {
                    includeSCT = false;
                    reference.setSCTURI(sct.getIdentifier().toString(), sct.getInstance());
                }
                secRef.setReference(reference);
                dktHeadrBlock =
                        new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), secRef, nonce, dkt.getOffset(), dkt.getLength(),dktId);
               
                //Construct the STR for Encryption
                DirectReference refEnc = new DirectReference();
                refEnc.setURI("#"+dktId);
                dktSctTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                dktSctTokenRef.setReference(refEnc);
               
            } else if (PolicyTypeUtil.issuedTokenKeyBinding(originalKeyBinding)) {
               
                issuedWithDKT = true;
               
                IssuedTokenContext trustContext =  context.getTrustContext();
                DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, trustContext.getProofKey());
                String dktId = secureMessage.generateId();
                String nonce = Base64.encode(dkt.getNonce());
               
                //get the symmetric key for encryption
                Key origKey = null;
                try{
                    origKey = new SecretKeySpec(trustContext.getProofKey(), SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
               
               
                //get the symmetric key for encryption key from derivedkeyToken
                try{
                    _symmetricKey = dkt.generateSymmetricKey(SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
               
                //Get the IssuedToken and insert it into the message
                GenericToken issuedToken = (GenericToken)trustContext.getSecurityToken();
               
                // check if the token is already present
                IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)originalKeyBinding;
                //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                String ikbPolicyId = ikb.getUUID();
                //Look for TrustToken in TokenCache
                HashMap tokCache = context.getTokenCache();
                Object tok = tokCache.get(ikbPolicyId);
               
                SecurityTokenReference str = null;
                Element strElem = null;
                String tokenVersion = ikb.getIncludeToken();
                includeIST = (IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_VER2.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(tokenVersion)
                          );
               
                if (includeIST && (issuedToken == null)) {
                    log.log(Level.SEVERE, "WSS1217.null.IssueToken");
                    throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                }
               
                if (issuedToken != null) {
                    // treat the token as an Opaque entity and just insert the token into message
                    Element elem = (Element)issuedToken.getTokenValue();
                    //TODO: remove these expensive conversions DOM Imports
                    if (tok == null) {
                        issuedTokenElement = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                        //Temp FIX for Issue#26: We need an Id to cache and MS not sending Id in some cases
                        String tokId = issuedTokenElement.getAttribute("Id");
                        if ("".equals(tokId) &&
                                MessageConstants.ENCRYPTED_DATA_LNAME.equals(issuedTokenElement.getLocalName())) {
                            issuedTokenElement.setAttribute("Id", secureMessage.generateId());
                        }
                        tokCache.put(ikbPolicyId, issuedTokenElement);
                    } else {
                        issuedTokenInserted = true;
                        // it will be SOAPElement retrieve its wsuId attr
                        String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                        issuedTokenElementFromMsg = secureMessage.getElementById(wsuId);
                        if (issuedTokenElementFromMsg == null) {
                            log.log(Level.SEVERE, "WSS1218.unableto.locate.IssueToken.Message");
                            throw new XWSSecurityException("Could not locate Issued Token in Message");
                        }
                    }
                }
               
                if (includeIST) {
                    if (trustContext.getAttachedSecurityTokenReference() != null) {
                        strElem = (Element)trustContext.getAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        log.log(Level.SEVERE, "WSS1219.unableto.refer.Attached.IssueToken");
                        throw new XWSSecurityException("Cannot determine how to reference the Attached Issued Token in the Message");
                    }
                } else {
                    //Trust Issued Token should not be in message at all, so use an external reference
                    if (trustContext.getUnAttachedSecurityTokenReference() != null) {
                        strElem = (Element)trustContext.getUnAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        log.log(Level.SEVERE, "WSS1220.unableto.refer.Un-Attached.IssueToken");
                        throw new XWSSecurityException("Cannot determine how to reference the Un-Attached Issued Token in the Message");
                    }
                }
               
                //TODO: remove these expensive conversions
                Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
                str = new SecurityTokenReference(
                        XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), (Element)imported.cloneNode(true)), false);
               
                if (origKey != null) {
                    SecurityUtil.updateSamlVsKeyCache(str, context, origKey);
                }
               
                dktHeadrBlock =
                        new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), str, nonce, dkt.getOffset(), dkt.getLength(),dktId);
                //Construct the STR for Encryption
                DirectReference refEnc = new DirectReference();
                refEnc.setURI("#"+dktId);
                dktIssuedTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                dktIssuedTokenRef.setReference(refEnc);
               
            }
        } else {
            log.log(Level.SEVERE, "WSS1222.unsupported.KeyBinding.EncryptionPolicy");
            throw new XWSSecurityException("Unsupported Key Binding for EncryptionPolicy");
        }
       
       
        XMLCipher _keyEncryptor = null;
        XMLCipher _dataEncryptor = null;
        Cipher _attachmentEncryptor = null;
        Cipher _dataCipher = null;
        try {
            // lazy n static instantiation can happen
            //TODO :: Algorithms -- Venu
            if(log.isLoggable(Level.FINEST)){
                log.log(Level.FINEST, "KeyEncryption algorithm is "+keyEncAlgo);
            }
           
            if (_x509Cert != null) {
                //prepare for keytransport
                _keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
                _keyEncryptor.init(XMLCipher.WRAP_MODE, _x509Cert.getPublicKey());
            } else if (samlkey != null) {
                //prepare for keytransport
                _keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
                _keyEncryptor.init(XMLCipher.WRAP_MODE, samlkey);
            }else if( keyEncSK != null){
                //prepare for keywrap
                _keyEncryptor = XMLCipher.getInstance(keyEncAlgo);
                _keyEncryptor.init(XMLCipher.WRAP_MODE, keyEncSK);
            }
           
            if(log.isLoggable(Level.FINEST)){
                log.log(Level.FINEST, "Data encryption algorithm is "+dataEncAlgo);
            }
           
            String dataAlgorithm =  JCEMapper.translateURItoJCEID(dataEncAlgo);
            _dataCipher = Cipher.getInstance(dataAlgorithm);
            _dataEncryptor = XMLCipher.getInstance(dataEncAlgo,_dataCipher);
            _dataCipher.init(XMLCipher.ENCRYPT_MODE, _symmetricKey);
            _dataEncryptor.init(XMLCipher.ENCRYPT_MODE, _symmetricKey);
           
        } catch (Exception xee) {
            log.log(Level.SEVERE, "WSS1205.unableto.initialize.xml.cipher",xee);
            throw new XWSSecurityException(
                    "Unable to initialize XML Cipher", xee);
        }
       
        ArrayList targets =  featureBinding.getTargetBindings();
       
        ArrayList _aparts = new ArrayList();
        ArrayList _dnodes = new ArrayList();
       
        Iterator i = targets.iterator();
        //TODO : remove all  the three while loops and
        //convert to a 2 loop - Venu
        while (i.hasNext()) {
            EncryptionTarget target = (EncryptionTarget)i.next();
            boolean contentOnly = target.getContentOnly();
            Boolean cOnly = Boolean.valueOf(contentOnly);
            if(MessageConstants.PROCESS_ALL_ATTACHMENTS.equals(target.getValue())){
                Iterator itr = secureMsg.getAttachments();
                while(itr.hasNext()){
                    AttachmentPart ap = (AttachmentPart)itr.next();
                    Object[] s = new Object[2];
                    s[0] = ap;
                    s[1] = cOnly;
                    _aparts.add(s);
                }
                continue;
            }
            Object mgpart = secureMsg.getMessageParts(target);
            //Change this to context.
            //TODO :: Venu
            ArrayList transforms = target.getCipherReferenceTransforms();
            if(mgpart == null){
                continue;
            } else if (mgpart instanceof AttachmentPart) {
                Object[] s = new Object[2];
                s[0] = mgpart;
                s[1] = cOnly;
                _aparts.add(s);
            } else{
                if (mgpart instanceof Node) {
                    Object[] s = new Object[2];
                    s[0] = mgpart;
                    s[1] = cOnly;
                    _dnodes.add(s);
                } else if (mgpart instanceof NodeList) {
                    for (int j=0; j<((NodeList)mgpart).getLength(); j++) {
                        Object[] s = new Object[2];
                        Node n = ((NodeList)mgpart).item(j);
                        s[0] = n;
                        s[1] = cOnly;
                        _dnodes.add(s);
                    }
                }
            }
        }
       
        if (_dnodes.isEmpty() && _aparts.isEmpty()) {
            if(log.isLoggable(Level.WARNING)){
                log.log(Level.WARNING, "None of the specified Encryption Parts found in the Message");
            }
        }
       
        EncryptedKey _encryptedKey = null;
        ReferenceListHeaderBlock _ekReferenceList = null;
        ReferenceListHeaderBlock _standaloneReferenceList = null;
       
        if (_keyEncryptor != null && !skbX509TokenInserted) {
            try {
                if(!dktSender){
                    _encryptedKey = _keyEncryptor.encryptKey(secureMsg.getSOAPPart(), _symmetricKey);
                } else{
                    _encryptedKey = _keyEncryptor.encryptKey(secureMsg.getSOAPPart(), originalKey);
                }
                _encryptedKey.setId(ekId);
                ekCache.put(x509TokenId, ekId);
                KeyInfoHeaderBlock keyInfoBlock = new KeyInfoHeaderBlock(secureMsg.getSOAPPart());
               
                if (samlTokenRef != null) {
                    keyInfoBlock.addSecurityTokenReference(samlTokenRef);
                } else if(_x509Cert != null){
                    keyInfoStrategy.insertKey(keyInfoBlock, secureMsg, x509TokenId);
                }else if(keyEncSK != null){
                    //keyInfoStrategy.insertKey(keyInfoBlock, secureMsg,null);
                    keyInfoBlock.addKeyName(symmetricKeyName);
                }
                KeyInfo keyInfo = keyInfoBlock.getKeyInfo(); /*new KeyInfo(keyInfoBlock.getAsSoapElement(), null); */
                _encryptedKey.setKeyInfo(keyInfo);
               
            } catch (Exception xe) {
                log.log(Level.SEVERE, "WSS1223.unableto.set.KeyInfo.EncryptedKey", xe);
                //xe.printStackTrace();
                throw new XWSSecurityException(xe);
            }
        }
       
        if (_encryptedKey != null && !dktSender && !useStandaloneRefList){
            _ekReferenceList = new ReferenceListHeaderBlock(secureMsg.getSOAPPart());
        }
        // process APs - push only EDs (create EDs), modify AP headers/content
       
        //When encrypting content and attachments with the same key process attachments first.
        //SWA Spec.
        SOAPElement x509Sibling = null;
       
        if(x509TokenElement != null){
            x509Sibling = (SOAPElement)x509TokenElement.getNextSibling();
        }
        Iterator _apartsI = _aparts.iterator();
        if(_apartsI.hasNext()){
            //We have attachments so get the cipher instances.
            try{
                //_attachmentEncryptor = Cipher.getInstance("DESede/CBC/ISO10126Padding");
                //TODO:GETMAP -venu
                String dataAlgorithm =  JCEMapper.translateURItoJCEID(dataEncAlgo);
                _attachmentEncryptor = Cipher.getInstance(dataAlgorithm);
                _attachmentEncryptor.init(Cipher.ENCRYPT_MODE, _symmetricKey);
            } catch (Exception xee) {
                log.log(Level.SEVERE, "WSS1205.unableto.initialize.xml.cipher", xee);
                throw new XWSSecurityException(
                        "Unable to initialize XML Cipher", xee);
            }
        }
        while (_apartsI.hasNext()) {
            Object[] s = (Object[])_apartsI.next();
            AttachmentPart p = (AttachmentPart)s[0];
            boolean b = ((Boolean)s[1]).booleanValue();
           
            // create n push an ED
           
            EncryptedDataHeaderBlock edhb = new EncryptedDataHeaderBlock();
           
            String id = secureMsg.generateId();
           
            edhb.setId(id);
            edhb.setType( (b ?  MessageConstants.ATTACHMENT_CONTENT_ONLY_URI : MessageConstants.ATTACHMENT_COMPLETE_URI));
            edhb.setMimeType(p.getContentType());
           
            String uri = p.getContentId();
            if (uri != null) {
                if ( uri.charAt(0) == '<' && uri.charAt(uri.length()-1) == '>'){
                    uri = "cid:" + uri.substring(1, uri.length()-1);
                }else{
                    uri = "cid:" + uri;
                }
            } else {
                uri = p.getContentLocation();
            }
           
            edhb.getCipherReference(true, uri);
            edhb.setEncryptionMethod(dataEncAlgo);
            edhb.addTransform(MessageConstants.ATTACHMENT_CONTENT_ONLY_TRANSFORM_URI);
           
            encryptAttachment(p, b, _attachmentEncryptor);
           
            if (_ekReferenceList != null){
                _ekReferenceList.addReference("#"+id);
            }
            if(x509Sibling == null && x509TokenElement == null){
                _secHeader.insertHeaderBlock(edhb);
            }else{
                if(x509Sibling != null){
                    _secHeader.insertBefore(edhb,x509Sibling);
                }else{
                    _secHeader.appendChild(edhb);
                }
            }
        }
        int optType = -1;
        Iterator _dnodeI = _dnodes.iterator();
        while (_dnodeI.hasNext()) {
            Object[] s = (Object[])_dnodeI.next();
            Node     n = (Node)s[0];
            boolean  b = ((Boolean)s[1]).booleanValue();
            //TODO :Add Transforms here.
            Element ed = null;
            boolean _fi = false;
            if(context.getConfigType() == MessageConstants.SIGN_ENCRYPT_BODY ){
                if(_fi){
                    ed = encryptBodyContent(secureMsg,context.getCanonicalizedData(),_dataEncryptor);
                }else{
                    signEncrypt(context, _dataCipher,_ekReferenceList,_standaloneReferenceList,keyInfoStrategy, dataEncAlgo);
                    continue;
                }
            }else{
                if(n.getNodeType() == Node.TEXT_NODE){
                    ed = encryptElement(secureMsg, (SOAPElement) n.getParentNode(),true, _dataEncryptor);
                }else{
                    ed = encryptElement(secureMsg, (SOAPElement)n, b, _dataEncryptor);
                }
            }
            EncryptedHeaderBlock ehb = null;
            boolean isEhb = false;
            EncryptedDataHeaderBlock xencEncryptedData = new EncryptedDataHeaderBlock(
                    XMLUtil.convertToSoapElement( secureMsg.getSOAPPart(), ed));
           
            String xencEncryptedDataId = secureMsg.generateId();
            String xencEncryptedDataRef = "#" + xencEncryptedDataId;
            if(ed.getParentNode() instanceof SOAPHeader && wss11Sender){
                isEhb = true;
                ehb = new EncryptedHeaderBlock(secureMsg.getSOAPPart());
                ehb.setId(xencEncryptedDataId);
                ehb.copyAttributes(secureMsg, _secHeader);
            }else{
                xencEncryptedData.setId(xencEncryptedDataId);
            }
           
            if (_ekReferenceList != null){
                _ekReferenceList.addReference(xencEncryptedDataRef);
            }else {
                if (_standaloneReferenceList == null){
                    _standaloneReferenceList = new ReferenceListHeaderBlock(secureMsg.getSOAPPart());
                }
                _standaloneReferenceList.addReference(xencEncryptedDataRef);
               
                KeyInfoHeaderBlock keyInfoBlock = new KeyInfoHeaderBlock(secureMsg.getSOAPPart());
                SecurityTokenReference cloned = null;
                if (dktSctTokenRef != null) {
                    cloned = new SecurityTokenReference((SOAPElement)dktSctTokenRef.cloneNode(true));
                    keyInfoBlock.addSecurityTokenReference(cloned);
                } else if (secConvRef != null) {
                    cloned = new SecurityTokenReference((SOAPElement)secConvRef.cloneNode(true));
                    keyInfoBlock.addSecurityTokenReference(cloned);
                } else if(ekTokenRef != null){
                    cloned = new SecurityTokenReference((SOAPElement)ekTokenRef.cloneNode(true));
                    keyInfoBlock.addSecurityTokenReference(cloned);
                } else if (dktIssuedTokenRef != null) {
                    cloned = new SecurityTokenReference((SOAPElement)dktIssuedTokenRef.cloneNode(true));
                    keyInfoBlock.addSecurityTokenReference(cloned);
                } else if (issuedTokenRef != null) {
                    cloned = new SecurityTokenReference((SOAPElement)issuedTokenRef.cloneNode(true));
                    keyInfoBlock.addSecurityTokenReference(cloned);
                } else {
                   
                    if (PolicyTypeUtil.x509CertificateBinding(keyBinding)){
                        //to handle EncryptBeforeSigning we split EK and RefList even in this case
                        DirectReference dRef = new DirectReference();
                        dRef.setURI("#"+ekId);
                        ekDirectRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                        ekDirectRef.setReference(dRef);
                        keyInfoBlock.addSecurityTokenReference(ekDirectRef);
                       
                    }else {
                        // this is the default KeyName case
                        keyInfoStrategy.insertKey(keyInfoBlock, secureMsg, null);
                    }
                   
                }
                xencEncryptedData.setKeyInfo(keyInfoBlock);
            }
           
            if(isEhb){
                try{
                    ed.getParentNode().replaceChild(ehb.getAsSoapElement(), ed);
                    ehb.addChildElement(xencEncryptedData.getAsSoapElement());
                }catch(Exception se){se.printStackTrace();}
            } else{
                ed.getParentNode().replaceChild(xencEncryptedData.getAsSoapElement(), ed);
            }
        }
       
        try {
            x509Sibling = null;
           
            if(x509TokenElement != null){
                x509Sibling = (SOAPElement)x509TokenElement.getNextSibling();
            }
           
            if (_encryptedKey != null) {
                SOAPElement se = (SOAPElement)_keyEncryptor.martial(_encryptedKey);
                se = _secHeader.makeUsable(se);
                if(_ekReferenceList != null)
                    se.appendChild(_ekReferenceList.getAsSoapElement());
               
                //store EKSHA1 of KeyValue contents in context
                Element cipherData = (Element)se.getChildElements(new QName(MessageConstants.XENC_NS, "CipherData", MessageConstants.XENC_PREFIX)).next();
                String cipherValue = cipherData.getElementsByTagNameNS(MessageConstants.XENC_NS, "CipherValue").item(0).getTextContent();
                byte[] decodedCipher = Base64.decode(cipherValue);
                byte[] ekSha1 = MessageDigest.getInstance("SHA-1").digest(decodedCipher);
                String encEkSha1 = Base64.encode(ekSha1);
                context.setExtraneousProperty("EncryptedKeySHA1", encEkSha1);
               
                if(x509Sibling == null ){
                    if(x509TokenElement == null){
                        _secHeader.insertHeaderBlockElement(se);
                    }else{
                        _secHeader.appendChild(se);
                    }
                }else{
                    _secHeader.insertBefore(se,x509Sibling);
                }
                //For SymmetricBinding  with X509 case and for Asym with E before S
                if (_standaloneReferenceList != null){
                    _secHeader.insertBefore(_standaloneReferenceList, se.getNextSibling());
                    context.setCurrentReferenceList(se.getNextSibling());
                }
            }else{
                if (_standaloneReferenceList != null){
                    // if  SCT or IssuedToken is not already in message then do what we did before WSIT
                    if ((sctElement == null) && (issuedTokenElementFromMsg == null)) {
                        if (insertedEkId != null) {
                            //insert the standalone reflist under EK
                            Element ekElem = secureMessage.getElementById(insertedEkId);
                            _secHeader.insertBefore(_standaloneReferenceList, ekElem.getNextSibling());
                           
                        } else {
                            _secHeader.insertHeaderBlock(_standaloneReferenceList);
                            context.setCurrentReferenceList(_standaloneReferenceList.getAsSoapElement());
                        }
                    } else {
                        // insert standalone reflist under the  SCT/Issued Token
                        if (sctElement != null) {
                            _secHeader.insertBefore(_standaloneReferenceList, sctElement.getNextSibling());
                        }else if (issuedTokenElementFromMsg != null) {
                            _secHeader.insertBefore(_standaloneReferenceList, issuedTokenElementFromMsg.getNextSibling());
                        } else {
                            _secHeader.insertHeaderBlock(_standaloneReferenceList);
                            context.setCurrentReferenceList(_standaloneReferenceList.getAsSoapElement());
                        }
                    }
                }
            }
           
            if (sctWithDKT || issuedWithDKT) {
                // SCT or IssuedToken not in message so insert it above the DKT in SecHeader
                if (sctElement == null && (sct != null)) {
                    _secHeader.insertHeaderBlock(dktHeadrBlock);
                    if (includeSCT) {
                        _secHeader.insertHeaderBlock(sct);
                    }
                } else if (issuedTokenElementFromMsg == null && (issuedTokenElement != null)) {
                    _secHeader.insertHeaderBlock(dktHeadrBlock);
                    if (includeIST) {
                        _secHeader.insertHeaderBlockElement(issuedTokenElement);
                    }
                    // also store the token in Packet.invocationProperties to be used by
                    // client side response processing
                    context.setIssuedSAMLToken(issuedTokenElement);
                } else {
                    // if the token is already in Message then insert DKT below it.
                    if (sctElement != null) {
                        _secHeader.insertBefore(dktHeadrBlock, sctElement.getNextSibling());
                    } else if (issuedTokenElementFromMsg != null) {
                        _secHeader.insertBefore(dktHeadrBlock, issuedTokenElementFromMsg.getNextSibling());
                    } else {
                        _secHeader.insertHeaderBlock(dktHeadrBlock);
                    }
                }
            } else {
                //Insert DKT here
                // insert the derivedKey into SecurityHeader
                if(dktHeadrBlock != null) {
                    if(insertedEkId != null) { //If DKT referes to EK
                        Element ekElem = secureMessage.getElementById(insertedEkId);
                        _secHeader.insertBefore(dktHeadrBlock, ekElem.getNextSibling());
                    } else{
                        _secHeader.insertHeaderBlock(dktHeadrBlock);
                    }
                }
View Full Code Here

    public static void process(FilterProcessingContext context) throws XWSSecurityException {
       
        //make a DynamicPolicyCallback to obtain the SAML assertion
       
        boolean isOptimized = false;
        SecurableSoapMessage secureMessage = null;
        SecurityHeader securityHeader = null;
        com.sun.xml.ws.security.opt.impl.outgoing.SecurityHeader optSecHeader = null;
        SecurityHeaderElement she = null;
        if(context instanceof JAXBFilterProcessingContext){
            isOptimized = true;
            optSecHeader = ((JAXBFilterProcessingContext)context).getSecurityHeader();
        } else{
            secureMessage = context.getSecurableSoapMessage();
            securityHeader = secureMessage.findOrCreateSecurityHeader();
        }
       
        AuthenticationTokenPolicy policy =
                (AuthenticationTokenPolicy)context.getSecurityPolicy();
        AuthenticationTokenPolicy.SAMLAssertionBinding samlPolicy =
                (AuthenticationTokenPolicy.SAMLAssertionBinding)policy.getFeatureBinding();
       
        if (samlPolicy.getIncludeToken() == samlPolicy.INCLUDE_ONCE) {
            throw new XWSSecurityException("Include Token ONCE not supported for SAMLToken Assertions");
        }
       
        if (samlPolicy.getAssertionType() !=
                AuthenticationTokenPolicy.SAMLAssertionBinding.SV_ASSERTION) {
            // should never be called this way
            throw new XWSSecurityException(
                    "Internal Error: ExportSamlAssertionFilter called for HOK assertion");
        }
       
        //AuthenticationTokenPolicy policyClone = (AuthenticationTokenPolicy)policy.clone();
        samlPolicy =
                (AuthenticationTokenPolicy.SAMLAssertionBinding)policy.getFeatureBinding();
        samlPolicy.isReadOnly(true);
       
        DynamicApplicationContext dynamicContext =
                new DynamicApplicationContext(context.getPolicyContext());
        dynamicContext.setMessageIdentifier(context.getMessageIdentifier());
        dynamicContext.inBoundMessage(false);
       
        AuthenticationTokenPolicy.SAMLAssertionBinding resolvedPolicy =
                context.getSecurityEnvironment().populateSAMLPolicy(context.getExtraneousProperties(), samlPolicy, dynamicContext);
       
        Assertion _assertion = null;
        Element assertionElement = resolvedPolicy.getAssertion();
        Element _authorityBinding = resolvedPolicy.getAuthorityBinding();
               
        if (assertionElement == null) {
            reader = resolvedPolicy.getAssertionReader();
            if (reader != null) {
                try {
                    reader.next(); //start document , so move to next event
                    id = reader.getAttributeValue(null, "AssertionID");
                    if (id == null) {
                        id = reader.getAttributeValue(null, "ID");
                    }
                    version = reader.getAttributeValue(null, "Version");
                    buffer = new MutableXMLStreamBuffer();
                    StreamWriterBufferCreator bCreator = new StreamWriterBufferCreator(buffer);
                    XMLStreamWriter writer_tmp = (XMLStreamWriter) bCreator;
                    while (!(XMLStreamReader.END_DOCUMENT == reader.getEventType())) {
                       com.sun.xml.ws.security.opt.impl.util.StreamUtil.writeCurrentEvent(reader, writer_tmp);
                       reader.next();                      
                    }
                } catch (XMLStreamException ex) {
                   throw new XWSSecurityException(ex);
                }
            }
        } else {
            try {
                if (System.getProperty("com.sun.xml.wss.saml.binding.jaxb") == null) {
                    if (assertionElement.getAttributeNode("ID") != null) {
                        _assertion = (Assertion) com.sun.xml.wss.saml.assertion.saml20.jaxb20.Assertion.fromElement(assertionElement);
                    } else {
                        _assertion = (Assertion) com.sun.xml.wss.saml.assertion.saml11.jaxb20.Assertion.fromElement(assertionElement);
                    }
                } else {
                    _assertion = (Assertion) com.sun.xml.wss.saml.assertion.saml11.jaxb10.Assertion.fromElement(assertionElement);
                }
            } catch (SAMLException ex) {
                //ignore
            }
        }

        if (samlPolicy.getIncludeToken() == samlPolicy.INCLUDE_NEVER ||
               samlPolicy.getIncludeToken() == samlPolicy.INCLUDE_NEVER_VER2 ) {
            if (_authorityBinding != null) {
                //nullify the assertion set by Callback since IncludeToken is never
                // do this because we have to maintain BackwardCompat with XWSS2.0
                assertionElement = null;
            }
        }
       
        if ((_assertion == null) && (_authorityBinding == null) && reader == null) {
            throw new XWSSecurityException(
                    "None of SAML Assertion,SAML Assertion Reader or  SAML AuthorityBinding information was set into " +
                    " the Policy by the CallbackHandler");
        }
       
        //TODO: check that the Confirmation Method of the assertion is indeed SV
        if (_assertion != null){
            if(_assertion.getVersion() == null && _authorityBinding == null){
                if(!isOptimized){
                    if ( System.getProperty("com.sun.xml.wss.saml.binding.jaxb") == null) {
                        ((com.sun.xml.wss.saml.assertion.saml11.jaxb20.Assertion)_assertion).toElement(securityHeader);
                    } else {
                        ((com.sun.xml.wss.saml.assertion.saml11.jaxb10.Assertion)_assertion).toElement(securityHeader);
                    }
                } else {
                    she = new GSHeaderElement(assertionElement, ((JAXBFilterProcessingContext) context).getSOAPVersion());
                    if (optSecHeader.getChildElement(she.getId()) == null) {
                        optSecHeader.add(she);
                    } else {
                        return;
                    }
                }
                HashMap tokenCache = context.getTokenCache();
                //assuming unique IDs
                tokenCache.put(((com.sun.xml.wss.saml.Assertion)_assertion).getAssertionID(), _assertion);
            } else if (_assertion.getVersion() != null){
                if(!isOptimized){
                    ((com.sun.xml.wss.saml.assertion.saml20.jaxb20.Assertion)_assertion).toElement(securityHeader);
                } else {
                    she = new GSHeaderElement(assertionElement, ((JAXBFilterProcessingContext) context).getSOAPVersion());
                    if (optSecHeader.getChildElement(she.getId()) == null) {
                        optSecHeader.add(she);
                    } else {
                        return;
                    }
                }
                HashMap tokenCache = context.getTokenCache();
                //assuming unique IDs
                tokenCache.put(((com.sun.xml.wss.saml.Assertion)_assertion).getID(), _assertion);
            else {
                //Authoritybinding is set. So the Assertion should not be exported
                if (null == resolvedPolicy.getSTRID()) {
                    throw new XWSSecurityException(
                            "Unsupported configuration: required wsu:Id value " +
                            " for SecurityTokenReference to Remote SAML Assertion not found " +
                            " in Policy");
                }
            }
        } else if(reader != null) {
            she = new GSHeaderElement(buffer);
            she.setId(id)// set the ID again to bring it to top
            if (optSecHeader.getChildElement(she.getId()) == null) {
                optSecHeader.add(she);
            } else {
                return;
            }
        }
       
        if (null != resolvedPolicy.getSTRID()) {
            //generate and export an STR into the Header with the given ID
            if ((_assertion == null) && (null == resolvedPolicy.getAssertionId()) && reader == null) {
                throw new XWSSecurityException(
                        "None of SAML Assertion, SAML Assertion Reader or SAML Assertion Id information was set into " +
                        " the Policy by the CallbackHandler");
            }
           
            String assertionId = resolvedPolicy.getAssertionId();
            if (_assertion != null) {
                assertionId = ((com.sun.xml.wss.saml.Assertion) _assertion).getAssertionID();
            } else {
                assertionId = (id != null) ? id : assertionId ;
            }
            if(!isOptimized){
                SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                tokenRef.setWsuId(resolvedPolicy.getSTRID());
                // set wsse11:TokenType to SAML1.1 or SAML2.0
                if(_assertion != null && _assertion.getVersion() != null){
                    tokenRef.setTokenType(MessageConstants.WSSE_SAML_v2_0_TOKEN_TYPE);
                } else {
                    if (reader != null) {                       
                        if (version == "2.0") {
                            tokenRef.setTokenType(MessageConstants.WSSE_SAML_v2_0_TOKEN_TYPE);
                        } else {
                            tokenRef.setTokenType(MessageConstants.WSSE_SAML_v1_1_TOKEN_TYPE);
                        }
                    } else {
                        tokenRef.setTokenType(MessageConstants.WSSE_SAML_v1_1_TOKEN_TYPE);
                    }
                }
               
                if (_authorityBinding != null) {
                    tokenRef.setSamlAuthorityBinding(_authorityBinding, secureMessage.getSOAPPart());
                }
               
                KeyIdentifierStrategy strat = new KeyIdentifierStrategy(assertionId);
                strat.insertKey(tokenRef, context.getSecurableSoapMessage());
                securityHeader.insertHeaderBlock(tokenRef);
View Full Code Here

TOP

Related Classes of com.sun.xml.wss.impl.SecurableSoapMessage

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.