Example usage for org.w3c.dom Element getNamespaceURI

List of usage examples for org.w3c.dom Element getNamespaceURI

Introduction

In this page you can find the example usage for org.w3c.dom Element getNamespaceURI.

Prototype

public String getNamespaceURI();

Source Link

Document

The namespace URI of this node, or null if it is unspecified (see ).

Usage

From source file:org.apache.webdav.lib.properties.AclProperty.java

/**
 * Parse a privilege element./*from  w ww  . ja v  a2s.  co  m*/
 */
protected Privilege parsePrivilege(Element privilegeElement) {
    return new Privilege(privilegeElement.getNamespaceURI(), privilegeElement.getLocalName(), null);
}

From source file:org.apache.woden.internal.DOMWSDLReader.java

protected DescriptionElement getWSDLFromLocation(String locationURI, DescriptionElement desc, Map wsdlModules)
        throws WSDLException {
    DescriptionElement referencedDesc = null;
    Element docEl;
    URL locationURL = null;/*from w  ww .j a  va 2s . c  om*/
    URI contextURI = null;

    try {
        /*
         * For simple resolvers, we resolve the parent (Description) URI
         * to be used as the context. This allows for relative locationURIs
         * to be resolved implicitly - they are considered to be located 
         * relative to the resolved parent. Therefore, relative URIs such as these
         * need not be listed in the catalog file.
         */

        /* TODO
         * OASIS-style catalogs have a convenience notation to define root URIs
         * thus grouping related URLs together. In this case the context URI here
         * should be left alone, but the resultant locationURL resolved instead.
         * 
         * Implement a boolean system property like org.apache.woden.resolver.useRelativeURLs
         * (set by the resolver ctor). SimpleURIResolver (et al) should set this to true,
         * OASISCatalogResolver should set to false. 
         */
        // contextURI = desc.getDocumentBaseURI();
        contextURI = resolveURI(desc.getDocumentBaseURI());
        URL contextURL = (contextURI != null) ? contextURI.toURL() : null;
        locationURL = StringUtils.getURL(contextURL, locationURI);
    } catch (MalformedURLException e) {
        String baseURI = contextURI != null ? contextURI.toString() : null;

        getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                "WSDL502", new Object[] { baseURI, locationURI }, ErrorReporter.SEVERITY_ERROR);

        //can't continue import with a bad URL.
        return null;
    }

    String locationStr = locationURL.toString();

    //Check if WSDL imported or included previously from this location.
    referencedDesc = (DescriptionElement) wsdlModules.get(locationStr);

    if (referencedDesc == null) {
        //not previously imported or included, so retrieve the WSDL.
        try {
            Document doc = getDocument(new InputSource(locationStr), locationStr);
            docEl = doc.getDocumentElement();
        } catch (IOException e) {
            //document retrieval failed (e.g. 'not found')
            getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                    "WSDL503", new Object[] { locationStr }, ErrorReporter.SEVERITY_WARNING, e);

            //cannot continue without the referenced document
            return null;
        }

        //The referenced document should contain a WSDL <description>
        QName docElQN = new QName(docEl.getNamespaceURI(), docEl.getLocalName());

        if (!Constants.Q_ELEM_DESCRIPTION.equals(docElQN)) {
            getErrorReporter().reportError(new ErrorLocatorImpl(), //TODO line&col nos.
                    "WSDL501", new Object[] { Constants.Q_ELEM_DESCRIPTION, docElQN },
                    ErrorReporter.SEVERITY_ERROR);

            //cannot continue without a <description> element
            return null;
        }

        XMLElement descEl = createXMLElement(docEl);

        referencedDesc = parseDescription(locationStr, descEl, wsdlModules);

        if (!wsdlModules.containsKey(locationStr)) {
            wsdlModules.put(locationStr, referencedDesc);
        }
    }

    return referencedDesc;
}

From source file:org.apache.ws.scout.registry.RegistryImpl.java

/**
 * /*from w  ww  .  j  a  v  a  2  s .c  o  m*/
 */
public JAXBElement<?> execute(JAXBElement<?> uddiRequest, URI endPointURI) throws RegistryException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document doc;
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        this.marshaller.marshal(uddiRequest, baos);
        doc = docBuilder.parse(new ByteArrayInputStream(baos.toByteArray()));
    } catch (SAXException saxe) {
        throw (new RegistryException(saxe));
    } catch (ParserConfigurationException pce) {
        throw (new RegistryException(pce));
    } catch (IOException ioe) {
        throw (new RegistryException(ioe));
    } catch (JAXBException ioe) {
        throw (new RegistryException(ioe));
    }
    Element request = doc.getDocumentElement();

    request.setAttribute("xmlns", this.getUddiNamespace());
    if (!"3.0".equals(this.getUddiVersion())) {
        request.setAttribute("generic", this.getUddiVersion());
    }
    //request.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns", this.getUddiNamespace());
    // A SOAP request is made and a SOAP response
    // is returned.

    Element response;
    try {
        response = transport.send(request, endPointURI);
    } catch (TransportException te) {
        throw new RegistryException(te);
    }
    /* if (response.hasAttributes()) {
        NamedNodeMap am = response.getAttributes();
        ArrayList<String> al = new ArrayList<String>();
        for (int i = 0; i < am.getLength(); i++) {
     Node n = am.item(i);
     String attribute = n.getNodeName();
     if (attribute!= null && attribute.startsWith("xmlns")) {
        al.add(attribute);
     }
        }
        for (String attr : al) {
     response.removeAttribute(attr);
        }
     }*/

    if (response.getNamespaceURI() == null) {
        response.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", this.getUddiNamespace());
    }

    // If we are getting responses from a UDDI v3, remove the xmlns

    // First, let's make sure that a response
    // (any response) is found in the SOAP Body.

    String responseName = response.getLocalName();
    if (responseName == null) {
        throw new RegistryException("Unsupported response " + "from registry. A value was not present.");
    }

    if (responseName.toLowerCase().equals("fault")) {
        NodeList nodeList = null;

        // Child Elements
        String fCode = null;
        nodeList = response.getElementsByTagName("faultcode");
        if (nodeList.getLength() > 0)
            fCode = nodeList.item(0).getNodeValue();

        String fString = null;
        nodeList = response.getElementsByTagName("faultstring");
        if (nodeList.getLength() > 0)
            fString = nodeList.item(0).getNodeValue();

        String fActor = null;
        nodeList = response.getElementsByTagName("faultactor");
        if (nodeList.getLength() > 0)
            fActor = nodeList.item(0).getNodeValue();

        DispositionReport dispRpt = null;

        nodeList = response.getElementsByTagName("detail");
        if (nodeList.getLength() > 0) {
            nodeList = ((Element) nodeList.item(0)).getElementsByTagName("dispositionReport");
            if (nodeList.getLength() > 0) {
                JAXBElement<DispositionReport> dispRptObj = null;
                try {
                    dispRptObj = (JAXBElement<DispositionReport>) unmarshaller
                            .unmarshal((Element) nodeList.item(0));
                } catch (JAXBException xmle) {
                    throw (new RegistryException(xmle));
                }
                dispRpt = dispRptObj.getValue();
            }
        }

        RegistryException e = new RegistryException(fCode, fString, fActor, dispRpt);

        // Create RegistryException instance and return
        throw e;
    }

    // Let's now try to determine which UDDI response
    // we received and unmarshal it appropriately or
    // throw a RegistryException if it's unknown.
    // Well, we have now determined that something was
    // returned and it is "a something" that we know
    // about so let's unmarshal it into a RegistryObject
    // Next, let's make sure we didn't recieve a SOAP
    // Fault. If it is a SOAP Fault then throw it
    // immediately.

    JAXBElement<?> uddiResponse = null;
    try {
        String xml = XMLUtils.convertNodeToXMLString(response);
        log.debug("Response is: " + xml);

        StringReader reader = new StringReader(xml);
        uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(new StreamSource(reader));
        //It is probably faster not to go to a String, but JAXB has issues with this
        //uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(response);

    } catch (JAXBException xmle) {
        throw (new RegistryException(xmle));
    }

    return uddiResponse;
}

From source file:org.apache.ws.scout.registry.RegistryV3Impl.java

/**
 * //w  ww .  j a  v a  2 s .c om
 */
public JAXBElement<?> execute(JAXBElement<?> uddiRequest, URI endPointURI) throws RegistryV3Exception {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document doc;
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        this.marshaller.marshal(uddiRequest, baos);
        doc = docBuilder.parse(new ByteArrayInputStream(baos.toByteArray()));
    } catch (SAXException saxe) {
        throw (new RegistryV3Exception(saxe));
    } catch (ParserConfigurationException pce) {
        throw (new RegistryV3Exception(pce));
    } catch (IOException ioe) {
        throw (new RegistryV3Exception(ioe));
    } catch (JAXBException ioe) {
        throw (new RegistryV3Exception(ioe));
    }
    Element request = doc.getDocumentElement();

    request.setAttribute("xmlns", this.getUddiNamespace());
    if (!"3.0".equals(this.getUddiVersion())) {
        request.setAttribute("generic", this.getUddiVersion());
    }
    //request.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns", this.getUddiNamespace());
    // A SOAP request is made and a SOAP response
    // is returned.
    if (log.isDebugEnabled()) {
        String xmlIn = XMLUtils.convertNodeToXMLString(request);
        log.debug("Request send to UDDI Registry: " + xmlIn);
    }

    Element response;
    try {
        response = transport.send(request, endPointURI);
    } catch (TransportException te) {
        throw new RegistryV3Exception(te);
    }
    /* if (response.hasAttributes()) {
       NamedNodeMap am = response.getAttributes();
       ArrayList<String> al = new ArrayList<String>();
       for (int i = 0; i < am.getLength(); i++) {
     Node n = am.item(i);
     String attribute = n.getNodeName();
     if (attribute!= null && attribute.startsWith("xmlns")) {
        al.add(attribute);
     }
       }
       for (String attr : al) {
     response.removeAttribute(attr);
       }
    }*/
    JAXBElement<?> uddiResponse = null;
    if (response != null) {
        if (response.getNamespaceURI() == null) {
            response.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", this.getUddiNamespace());
        }

        // If we are getting responses from a UDDI v3, remove the xmlns

        // First, let's make sure that a response
        // (any response) is found in the SOAP Body.

        String responseName = response.getLocalName();
        if (responseName == null) {
            throw new RegistryV3Exception("Unsupported response " + "from registry. A value was not present.");
        }

        // Let's now try to determine which UDDI response
        // we received and unmarshal it appropriately or
        // throw a RegistryV3Exception if it's unknown.
        // Well, we have now determined that something was
        // returned and it is "a something" that we know
        // about so let's unmarshal it into a RegistryObject
        // Next, let's make sure we didn't recieve a SOAP
        // Fault. If it is a SOAP Fault then throw it
        // immediately.

        try {
            String xml = XMLUtils.convertNodeToXMLString(response);
            log.debug("Response is: " + xml);

            StringReader reader = new StringReader(xml);
            uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(new StreamSource(reader));
            //It is probably faster not to go to a String, but JAXB has issues with this
            //uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(response);

        } catch (JAXBException xmle) {
            throw (new RegistryV3Exception(xmle));
        }

        if (responseName.toLowerCase().equals("fault")) {
            NodeList nodeList = null;

            // Child Elements
            String fCode = null;
            nodeList = response.getElementsByTagName("faultcode");
            if (nodeList.getLength() > 0)
                fCode = nodeList.item(0).getNodeValue();

            String fString = null;
            nodeList = response.getElementsByTagName("faultstring");
            if (nodeList.getLength() > 0)
                fString = nodeList.item(0).getNodeValue();

            String fActor = null;
            nodeList = response.getElementsByTagName("faultactor");
            if (nodeList.getLength() > 0)
                fActor = nodeList.item(0).getNodeValue();

            DispositionReport dispRpt = null;

            nodeList = response.getElementsByTagName("detail");
            if (nodeList.getLength() > 0) {
                nodeList = ((Element) nodeList.item(0)).getElementsByTagName("dispositionReport");
                if (nodeList.getLength() > 0) {
                    JAXBElement<DispositionReport> dispRptObj = null;
                    try {
                        dispRptObj = (JAXBElement<DispositionReport>) unmarshaller
                                .unmarshal((Element) nodeList.item(0));
                    } catch (JAXBException xmle) {
                        throw (new RegistryV3Exception(xmle));
                    }
                    dispRpt = dispRptObj.getValue();
                }
            }

            RegistryV3Exception e = new RegistryV3Exception(fCode, fString, fActor, dispRpt);

            // Create RegistryV3Exception instance and return
            throw e;
        }
    }

    return uddiResponse;
}

From source file:org.apache.ws.security.message.TestMessageTransformer.java

private static void search(List<Element> list, Element baseElement, QName nodeName, boolean recursive) {
    if (nodeName == null) {
        list.add(baseElement);/*from   w  w  w  .  j  a  v  a2s .co  m*/
    } else {
        QName qname;
        if (nodeName.getNamespaceURI().length() > 0) {
            qname = new QName(baseElement.getNamespaceURI(), baseElement.getLocalName());
        } else {
            qname = new QName(baseElement.getLocalName());
        }
        if (qname.equals(nodeName)) {
            list.add(baseElement);
        }
    }
    if (recursive) {
        NodeList nlist = baseElement.getChildNodes();
        int len = nlist.getLength();
        for (int i = 0; i < len; i++) {
            Node child = nlist.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                search(list, (Element) child, nodeName, recursive);
            }
        }
    }
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

private Document buildEmbedded(Document doc) throws WSSecurityException {
    doDebug = log.isDebugEnabled();/*  w  w  w  .  j a  v a2  s .  c  o  m*/

    long t0 = 0, t1 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }

    /*
     * Second step: generate a symmetric key from the specified
     * key (password) for this algorithm, and set the cipher into
     * encryption mode.
     */
    this.encryptionKey = this.symmetricKey;
    if (this.encryptionKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.encryptionKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
    }

    KeyInfo keyInfo = null;
    if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
        keyInfo = new KeyInfo(doc);
        keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
    } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        /* This means that we want to embed a <wsse:SecurityTokenReference>
        * into keyInfo element.
        * If we need this functionality, this.secRef MUST be set before
        * calling the build(doc, crypto) method.
        * So if secRef is null then throw an exception.
        */
        if (this.securityTokenReference == null) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                    "You must set keyInfo element, if the keyIdentifier " + "== EMBED_SECURITY_TOKEN_REF");
        } else {
            keyInfo = new KeyInfo(doc);
            Element tmpE = securityTokenReference.getElement();
            tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI());
            keyInfo.addUnknownElement(securityTokenReference.getElement());
        }
    }

    Vector encDataRefs = doEncryption(doc, this.encryptionKey, keyInfo);

    /*
     * At this point data is encrypted with the symmetric key and can be
     * referenced via the above Id
     */

    /*
     * Now we need to setup the wsse:Security header block
     * 1) get (or create) the wsse:Security header block
     * 2) The last step sets up the reference list that pints to the encrypted
     *    data that was encrypted with this encrypted session key :-)
     */
    Element wsseSecurity = insertSecurityHeader(doc);

    Element tmpE = doc.createElement("temp");
    Element refList = createDataRefList(doc, tmpE, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, refList);

    if (tlog.isDebugEnabled()) {
        tlog.debug("EncryptBody embedded: symm-enc " + (t1 - t0));
    }
    return doc;
}

From source file:org.apache.ws.security.message.WSSecEncrypt.java

private Document buildEmbedded(Document doc, WSSecHeader secHeader) throws WSSecurityException {
    doDebug = log.isDebugEnabled();/*from  w  ww .  ja  va 2 s.c o m*/

    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }
    envelope = doc.getDocumentElement();
    envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);

    //
    // Second step: generate a symmetric key from the specified key
    // (password) for this algorithm, and set the cipher into encryption
    // mode.
    //
    if (this.symmetricKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
    }

    KeyInfo keyInfo = null;
    if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
        keyInfo = new KeyInfo(doc);
        keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
    } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        //
        // This means that we want to embed a <wsse:SecurityTokenReference>
        // into keyInfo element. If we need this functionality, this.secRef
        // MUST be set before calling the build(doc, crypto) method. So if
        // secRef is null then throw an exception.
        //
        if (this.securityTokenReference == null) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                    "You must set keyInfo element, if the keyIdentifier == EMBED_SECURITY_TOKEN_REF");
        } else {
            keyInfo = new KeyInfo(doc);
            Element tmpE = securityTokenReference.getElement();
            tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI());
            keyInfo.addUnknownElement(securityTokenReference.getElement());
        }
    }
    Element keyInfoElement = keyInfo.getElement();
    keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS);

    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
    if (parts == null) {
        parts = new Vector();
        WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content");
        parts.add(encP);
    }
    Vector encDataRefs = doEncryption(doc, this.symmetricKey, keyInfo, parts);

    //
    // At this point data is encrypted with the symmetric key and can be
    // referenced via the above Id
    //

    //
    // Now we need to setup the wsse:Security header block 1) get (or
    // create) the wsse:Security header block 2) The last step sets up the
    // reference list that pints to the encrypted data
    //
    Element wsseSecurity = secHeader.getSecurityHeader();

    Element referenceList = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":ReferenceList");
    referenceList = createDataRefList(doc, referenceList, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, referenceList);

    return doc;
}

From source file:org.apache.ws.security.processor.EncryptedDataProcessor.java

public List<WSSecurityEngineResult> handleToken(Element elem, RequestData request, WSDocInfo wsDocInfo)
        throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Found EncryptedData element");
    }//from w  ww.j a  v  a  2  s.c om
    Element kiElem = WSSecurityUtil.getDirectChildElement(elem, "KeyInfo", WSConstants.SIG_NS);
    // KeyInfo cannot be null
    if (kiElem == null) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noKeyinfo");
    }

    String symEncAlgo = X509Util.getEncAlgo(elem);
    // Check BSP compliance
    if (request.getWssConfig().isWsiBSPCompliant()) {
        checkBSPCompliance(symEncAlgo);
    }

    // Get the Key either via a SecurityTokenReference or an EncryptedKey
    Element secRefToken = WSSecurityUtil.getDirectChildElement(kiElem, "SecurityTokenReference",
            WSConstants.WSSE_NS);
    Element encryptedKeyElement = WSSecurityUtil.getDirectChildElement(kiElem, WSConstants.ENC_KEY_LN,
            WSConstants.ENC_NS);

    if (elem != null && request.isRequireSignedEncryptedDataElements()) {
        WSSecurityUtil.verifySignedElement(elem, elem.getOwnerDocument(), wsDocInfo.getSecurityHeader());
    }

    SecretKey key = null;
    List<WSSecurityEngineResult> encrKeyResults = null;
    Principal principal = null;
    if (secRefToken != null) {
        STRParser strParser = new SecurityTokenRefSTRParser();
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo);
        strParser.parseSecurityTokenReference(secRefToken, request, wsDocInfo, parameters);
        byte[] secretKey = strParser.getSecretKey();
        principal = strParser.getPrincipal();
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, secretKey);
    } else if (encryptedKeyElement != null) {
        EncryptedKeyProcessor encrKeyProc = new EncryptedKeyProcessor();
        encrKeyResults = encrKeyProc.handleToken(encryptedKeyElement, request, wsDocInfo);
        byte[] symmKey = (byte[]) encrKeyResults.get(0).get(WSSecurityEngineResult.TAG_SECRET);
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, symmKey);
    } else {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncKey");
    }

    // Check for compliance against the defined AlgorithmSuite
    AlgorithmSuite algorithmSuite = request.getAlgorithmSuite();
    if (algorithmSuite != null) {
        AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite);

        if (principal instanceof WSDerivedKeyTokenPrincipal) {
            algorithmSuiteValidator
                    .checkDerivedKeyAlgorithm(((WSDerivedKeyTokenPrincipal) principal).getAlgorithm());
            algorithmSuiteValidator
                    .checkEncryptionDerivedKeyLength(((WSDerivedKeyTokenPrincipal) principal).getLength());
        }
        algorithmSuiteValidator.checkSymmetricKeyLength(key.getEncoded().length);
        algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo);
    }

    // initialize Cipher ....
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.setSecureValidation(true);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, key);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }
    Node previousSibling = elem.getPreviousSibling();
    Node parent = elem.getParentNode();
    try {
        xmlCipher.doFinal(elem.getOwnerDocument(), elem, false);
    } catch (Exception e) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
    }

    WSDataRef dataRef = new WSDataRef();
    dataRef.setWsuId(elem.getAttributeNS(null, "Id"));
    dataRef.setAlgorithm(symEncAlgo);
    dataRef.setContent(false);

    Node decryptedNode;
    if (previousSibling == null) {
        decryptedNode = parent.getFirstChild();
    } else {
        decryptedNode = previousSibling.getNextSibling();
    }
    if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
        dataRef.setProtectedElement((Element) decryptedNode);
    }
    dataRef.setXpath(ReferenceListProcessor.getXPath(decryptedNode));

    WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.ENCR,
            Collections.singletonList(dataRef));
    result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id"));
    wsDocInfo.addResult(result);
    wsDocInfo.addTokenElement(elem);

    WSSConfig wssConfig = request.getWssConfig();
    if (wssConfig != null) {
        // Get hold of the plain text element
        Element decryptedElem;
        if (previousSibling == null) {
            decryptedElem = (Element) parent.getFirstChild();
        } else {
            decryptedElem = (Element) previousSibling.getNextSibling();
        }
        QName el = new QName(decryptedElem.getNamespaceURI(), decryptedElem.getLocalName());
        Processor proc = request.getWssConfig().getProcessor(el);
        if (proc != null) {
            if (log.isDebugEnabled()) {
                log.debug("Processing decrypted element with: " + proc.getClass().getName());
            }
            List<WSSecurityEngineResult> results = proc.handleToken(decryptedElem, request, wsDocInfo);
            List<WSSecurityEngineResult> completeResults = new ArrayList<WSSecurityEngineResult>();
            if (encrKeyResults != null) {
                completeResults.addAll(encrKeyResults);
            }
            completeResults.add(result);
            completeResults.addAll(0, results);
            return completeResults;
        }
    }
    encrKeyResults.add(result);
    return encrKeyResults;
}

From source file:org.apache.ws.security.processor.EncryptedKeyProcessor.java

public ArrayList handleEncryptedKey(Element xencEncryptedKey, CallbackHandler cb, Crypto crypto,
        PrivateKey privateKey) throws WSSecurityException {
    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }//  w ww.j  av  a2  s.  c o  m
    // need to have it to find the encrypted data elements in the envelope
    Document doc = xencEncryptedKey.getOwnerDocument();

    // lookup xenc:EncryptionMethod, get the Algorithm attribute to determine
    // how the key was encrypted. Then check if we support the algorithm

    Node tmpE = null; // short living Element used for lookups only
    tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "EncryptionMethod",
            WSConstants.ENC_NS);
    if (tmpE != null) {
        this.encryptedKeyTransportMethod = ((Element) tmpE).getAttribute("Algorithm");
    }
    if (this.encryptedKeyTransportMethod == null) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncAlgo");
    }
    Cipher cipher = WSSecurityUtil.getCipherInstance(this.encryptedKeyTransportMethod);
    //
    // Well, we can decrypt the session (symmetric) key. Now lookup CipherValue, this is the 
    // value of the encrypted session key (session key usually is a symmetrical key that encrypts
    // the referenced content). This is a 2-step lookup
    //
    Element xencCipherValue = null;
    tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "CipherData", WSConstants.ENC_NS);
    if (tmpE != null) {
        xencCipherValue = (Element) WSSecurityUtil.getDirectChild(tmpE, "CipherValue", WSConstants.ENC_NS);
    }
    if (xencCipherValue == null) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noCipher");
    }

    if (privateKey == null) {
        Element keyInfo = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "KeyInfo",
                WSConstants.SIG_NS);
        String alias;
        if (keyInfo != null) {
            Element secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo, "SecurityTokenReference",
                    WSConstants.WSSE_NS);
            //
            // EncryptedKey must a a STR as child of KeyInfo, KeyName  
            // valid only for EncryptedData
            //
            //  if (secRefToken == null) {
            //      secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo,
            //              "KeyName", WSConstants.SIG_NS);
            //  }
            if (secRefToken == null) {
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noSecTokRef");
            }
            SecurityTokenReference secRef = new SecurityTokenReference(secRefToken);
            //
            // Well, at this point there are several ways to get the key.
            // Try to handle all of them :-).
            //
            alias = null;
            //
            // handle X509IssuerSerial here. First check if all elements are available,
            // get the appropriate data, check if all data is available.
            // If all is ok up to that point, look up the certificate alias according
            // to issuer name and serial number.
            // This method is recommended by OASIS WS-S specification, X509 profile
            //
            if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
                alias = secRef.getX509IssuerSerialAlias(crypto);
                if (log.isDebugEnabled()) {
                    log.debug("X509IssuerSerial alias: " + alias);
                }
            }
            //
            // If wsse:KeyIdentifier found, then the public key of the attached cert was used to
            // encrypt the session (symmetric) key that encrypts the data. Extract the certificate
            // using the BinarySecurity token (was enhanced to handle KeyIdentifier too).
            // This method is _not_ recommended by OASIS WS-S specification, X509 profile
            //
            else if (secRef.containsKeyIdentifier()) {
                X509Certificate[] certs = null;
                if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                    Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb);

                    if (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                    }
                    SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                    Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb);
                    if (crypto == null) {
                        throw new WSSecurityException(0, "noSigCryptoFile");
                    }
                    SAML2KeyInfo samlKi = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                } else {
                    certs = secRef.getKeyIdentifier(crypto);
                }
                if (certs == null || certs.length < 1 || certs[0] == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                            new Object[] { "decryption (KeyId)" });
                }
                //
                // Here we have the certificate. Now find the alias for it. Needed to identify
                // the private key associated with this certificate
                //
                alias = crypto.getAliasForX509Cert(certs[0]);
                cert = certs[0];
                if (log.isDebugEnabled()) {
                    log.debug("cert: " + certs[0]);
                    log.debug("KeyIdentifier Alias: " + alias);
                }
            } else if (secRef.containsReference()) {
                Element bstElement = secRef.getTokenElement(doc, null, cb);

                // at this point ... check token type: Binary
                QName el = new QName(bstElement.getNamespaceURI(), bstElement.getLocalName());
                if (el.equals(WSSecurityEngine.binaryToken)) {
                    X509Security token = new X509Security(bstElement);
                    String value = bstElement.getAttribute(WSSecurityEngine.VALUE_TYPE);
                    if (!X509Security.X509_V3_TYPE.equals(value) || (token == null)) {
                        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                                "unsupportedBinaryTokenType", new Object[] { "for decryption (BST)" });
                    }
                    cert = token.getX509Certificate(crypto);
                    if (cert == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound",
                                new Object[] { "decryption" });
                    }
                    //
                    // Here we have the certificate. Now find the alias for it. Needed to identify
                    // the private key associated with this certificate
                    //
                    alias = crypto.getAliasForX509Cert(cert);
                    if (log.isDebugEnabled()) {
                        log.debug("BST Alias: " + alias);
                    }
                } else {
                    throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                            "unsupportedBinaryTokenType", null);
                }
                //
                // The following code is somewhat strange: the called crypto method gets
                // the keyname and searches for a certificate with an issuer's name that is
                // equal to this keyname. No serialnumber is used - IMHO this does
                // not identifies a certificate. In addition neither the WSS4J encryption
                // nor signature methods use this way to identify a certificate. Because of that
                // the next lines of code are disabled.  
                //
                // } else if (secRef.containsKeyName()) {
                //    alias = crypto.getAliasForX509Cert(secRef.getKeyNameValue());
                //    if (log.isDebugEnabled()) {
                //        log.debug("KeyName alias: " + alias);
                //    }
            } else {
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyId");
            }
        } else if (crypto.getDefaultX509Alias() != null) {
            alias = crypto.getDefaultX509Alias();
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noKeyinfo");
        }
        //
        // At this point we have all information necessary to decrypt the session
        // key:
        // - the Cipher object intialized with the correct methods
        // - The data that holds the encrypted session key
        // - the alias name for the private key
        //
        // Now use the callback here to get password that enables
        // us to read the private key
        //
        WSPasswordCallback pwCb = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT);
        try {
            Callback[] callbacks = new Callback[] { pwCb };
            cb.handle(callbacks);
        } catch (IOException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e);
        } catch (UnsupportedCallbackException e) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e);
        }
        String password = pwCb.getPassword();
        if (password == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias });
        }

        try {
            privateKey = crypto.getPrivateKey(alias, password);
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
        }
    }

    try {
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
    } catch (Exception e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1);
    }

    try {
        encryptedEphemeralKey = getDecodedBase64EncodedData(xencCipherValue);
        decryptedBytes = cipher.doFinal(encryptedEphemeralKey);
    } catch (IllegalStateException e2) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e2);
    } catch (Exception e2) {
        decryptedBytes = getRandomKey(getDataRefURIs(xencCipherValue), xencEncryptedKey.getOwnerDocument(),
                docInfo);
    }

    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    // At this point we have the decrypted session (symmetric) key. According
    // to W3C XML-Enc this key is used to decrypt _any_ references contained in
    // the reference list
    // Now lookup the references that are encrypted with this key
    //
    Element refList = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "ReferenceList",
            WSConstants.ENC_NS);
    ArrayList dataRefs = new ArrayList();
    if (refList != null) {
        for (tmpE = refList.getFirstChild(); tmpE != null; tmpE = tmpE.getNextSibling()) {
            if (tmpE.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            if (!tmpE.getNamespaceURI().equals(WSConstants.ENC_NS)) {
                continue;
            }
            if (tmpE.getLocalName().equals("DataReference")) {
                String dataRefURI = ((Element) tmpE).getAttribute("URI");
                if (dataRefURI.charAt(0) == '#') {
                    dataRefURI = dataRefURI.substring(1);
                }
                WSDataRef dataRef = decryptDataRef(doc, dataRefURI, decryptedBytes);
                dataRefs.add(dataRef);
            }
        }
        return dataRefs;
    }

    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug(
                "XMLDecrypt: total= " + (t2 - t0) + ", get-sym-key= " + (t1 - t0) + ", decrypt= " + (t2 - t1));
    }

    return null;
}

From source file:org.apache.ws.security.processor.SignatureProcessor.java

/**
 * Verify the WS-Security signature.//from  w w w . j  a v  a2 s .co m
 * 
 * The functions at first checks if then <code>KeyInfo</code> that is
 * contained in the signature contains standard X509 data. If yes then
 * get the certificate data via the standard <code>KeyInfo</code> methods.
 * 
 * Otherwise, if the <code>KeyInfo</code> info does not contain X509 data, check
 * if we can find a <code>wsse:SecurityTokenReference</code> element. If yes, the next
 * step is to check how to get the certificate. Two methods are currently supported
 * here:
 * <ul>
 * <li> A URI reference to a binary security token contained in the <code>wsse:Security
 * </code> header.  If the dereferenced token is
 * of the correct type the contained certificate is extracted.
 * </li>
 * <li> Issuer name an serial number of the certificate. In this case the method
 * looks up the certificate in the keystore via the <code>crypto</code> parameter.
 * </li>
 * </ul>
 * 
 * The methods checks is the certificate is valid and calls the
 * {@link org.apache.xml.security.signature.XMLSignature#checkSignatureValue(X509Certificate) 
 * verification} function.
 *
 * @param elem        the XMLSignature DOM Element.
 * @param crypto      the object that implements the access to the keystore and the
 *                    handling of certificates.
 * @param returnCert  verifyXMLSignature stores the certificate in the first
 *                    entry of this array. The caller may then further validate
 *                    the certificate
 * @param returnElements verifyXMLSignature adds the wsu:ID attribute values for
 *               the signed elements to this Set
 * @param cb CallbackHandler instance to extract key passwords
 * @return the subject principal of the validated X509 certificate (the
 *         authenticated subject). The calling function may use this
 *         principal for further authentication or authorization.
 * @throws WSSecurityException
 */
protected Principal verifyXMLSignature(Element elem, Crypto crypto, X509Certificate[] returnCert,
        Set returnElements, List protectedElements, byte[][] signatureValue, CallbackHandler cb,
        WSDocInfo wsDocInfo) throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Verify XML Signature");
    }
    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }

    XMLSignature sig = null;
    try {
        sig = new XMLSignature(elem, null);
    } catch (XMLSecurityException e2) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noXMLSig", null, e2);
    }

    sig.addResourceResolver(EnvelopeIdResolver.getInstance());

    KeyInfo info = sig.getKeyInfo();
    UsernameToken ut = null;
    DerivedKeyToken dkt = null;
    SAMLKeyInfo samlKi = null;
    SAML2KeyInfo saml2Ki = null;
    String customTokenId = null;
    java.security.PublicKey publicKey = null;
    X509Certificate[] certs = null;
    boolean validateCertificateChain = false;
    boolean kerbThumbPrint = false;
    X509Certificate cert = null;

    try {
        cert = info.getX509Certificate();
    } catch (KeyResolverException ignore) {
        if (log.isDebugEnabled()) {
            log.debug(ignore);
        }
    }

    if (info != null && info.containsKeyValue()) {
        try {
            publicKey = info.getPublicKey();
        } catch (Exception ex) {
            throw new WSSecurityException(ex.getMessage(), ex);
        }
    } else if (info != null && cert != null) {
        certs = new X509Certificate[] { cert };
    } else if (info != null) {
        Node node = WSSecurityUtil.getDirectChild(info.getElement(),
                SecurityTokenReference.SECURITY_TOKEN_REFERENCE, WSConstants.WSSE_NS);
        if (node == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
        SecurityTokenReference secRef = new SecurityTokenReference((Element) node);
        //
        // Here we get some information about the document that is being
        // processed, in particular the crypto implementation, and already
        // detected BST that may be used later during dereferencing.
        //
        if (secRef.containsReference()) {
            org.apache.ws.security.message.token.Reference ref = secRef.getReference();
            Element krbToken = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

            if (krbToken.getAttribute("ValueType").equals(
                    "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ")) {

                KerberosTokenProcessor krbp = new KerberosTokenProcessor(this.returnResults);
                return krbp.verifyXMLSignature(elem, crypto, returnCert, returnElements, protectedElements,
                        signatureValue, cb);
            }

            String uri = ref.getURI();
            if (uri.charAt(0) == '#') {
                uri = uri.substring(1);
            }
            Processor processor = wsDocInfo.getProcessor(uri);
            if (processor == null) {
                Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                //
                // at this point check token type: Binary, SAML, EncryptedKey, Custom
                //
                QName el = new QName(token.getNamespaceURI(), token.getLocalName());
                if (el.equals(WSSecurityEngine.binaryToken)) {
                    certs = getCertificatesTokenReference(token, crypto);
                    if (certs != null && certs.length > 1) {
                        validateCertificateChain = true;
                    }
                } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                    samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                    secretKey = samlKi.getSecret();
                } else if (el.equals(WSSecurityEngine.SAML2_TOKEN)) {
                    saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                    certs = saml2Ki.getCerts();
                    secretKey = saml2Ki.getSecret();

                } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {
                    if (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                    }
                    EncryptedKeyProcessor encryptKeyProcessor = new EncryptedKeyProcessor();
                    encryptKeyProcessor.handleEncryptedKey(token, cb, crypto);
                    secretKey = encryptKeyProcessor.getDecryptedBytes();
                } else {
                    // Try custom token through callback handler
                    // try to find a custom token
                    String id = secRef.getReference().getURI();
                    if (id.charAt(0) == '#') {
                        id = id.substring(1);
                    }
                    WSPasswordCallback pwcb = new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
                    try {
                        Callback[] callbacks = new Callback[] { pwcb };
                        cb.handle(callbacks);
                    } catch (Exception e) {
                        throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                                new Object[] { id }, e);
                    }

                    secretKey = pwcb.getKey();
                    customTokenId = id;
                    if (secretKey == null) {
                        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
                                "unsupportedKeyInfo", new Object[] { el.toString() });
                    }
                }
            } else if (processor instanceof UsernameTokenProcessor) {
                ut = ((UsernameTokenProcessor) processor).getUt();
                if (ut.isDerivedKey()) {
                    secretKey = ut.getDerivedKey();
                } else {
                    secretKey = ut.getSecretKey(secretKeyLength);
                }
            } else if (processor instanceof BinarySecurityTokenProcessor) {
                certs = ((BinarySecurityTokenProcessor) processor).getCertificates();
                if (certs != null && certs.length > 1) {
                    validateCertificateChain = true;
                }
            } else if (processor instanceof EncryptedKeyProcessor) {
                EncryptedKeyProcessor ekProcessor = (EncryptedKeyProcessor) processor;
                secretKey = ekProcessor.getDecryptedBytes();
                customTokenId = ekProcessor.getId();
            } else if (processor instanceof SecurityContextTokenProcessor) {
                SecurityContextTokenProcessor sctProcessor = (SecurityContextTokenProcessor) processor;
                secretKey = sctProcessor.getSecret();
                customTokenId = sctProcessor.getIdentifier();
            } else if (processor instanceof DerivedKeyTokenProcessor) {
                DerivedKeyTokenProcessor dktProcessor = (DerivedKeyTokenProcessor) processor;
                String signatureMethodURI = sig.getSignedInfo().getSignatureMethodURI();
                dkt = dktProcessor.getDerivedKeyToken();
                int keyLength = (dkt.getLength() > 0) ? dkt.getLength()
                        : WSSecurityUtil.getKeyLength(signatureMethodURI);

                secretKey = dktProcessor.getKeyBytes(keyLength);
            } else if (processor instanceof SAMLTokenProcessor) {
                if (crypto == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
                }
                SAMLTokenProcessor samlp = (SAMLTokenProcessor) processor;
                samlKi = SAMLUtil.getSAMLKeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (processor instanceof SAML2TokenProcessor) {
                if (crypto == null)
                    throw new WSSecurityException(0, "noSigCryptoFile");
                SAML2TokenProcessor samlp = (SAML2TokenProcessor) processor;
                saml2Ki = SAML2Util.getSAML2KeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            }
        } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
            certs = secRef.getX509IssuerSerial(crypto);
        } else if (secRef.containsKeyIdentifier()) {
            if (secRef.getKeyIdentifierValueType().equals(SecurityTokenReference.ENC_KEY_SHA1_URI)) {
                String id = secRef.getKeyIdentifierValue();
                WSPasswordCallback pwcb = new WSPasswordCallback(id, null,
                        SecurityTokenReference.ENC_KEY_SHA1_URI, WSPasswordCallback.ENCRYPTED_KEY_TOKEN);
                try {
                    Callback[] callbacks = new Callback[] { pwcb };
                    cb.handle(callbacks);
                } catch (Exception e) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword",
                            new Object[] { id }, e);
                }
                secretKey = pwcb.getKey();
            } else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);

                samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                certs = samlKi.getCerts();
                secretKey = samlKi.getSecret();
                publicKey = samlKi.getPublicKey();
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                Element token = secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                saml2Ki = SAML2Util.getSAML2KeyInfo(token, crypto, cb);
                certs = saml2Ki.getCerts();
                secretKey = saml2Ki.getSecret();
            } else {
                certs = secRef.getKeyIdentifier(crypto);
                if (certs == null && secRef.containsKerberosThumbprint()) {
                    secretKey = secRef.getKerberosSession().getSessionKey().getEncoded();
                    kerbThumbPrint = true;
                }
            }
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo",
                    new Object[] { node.toString() });
        }
    } else {
        if (crypto == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
        }
        if (crypto.getDefaultX509Alias() != null) {
            certs = crypto.getCertificates(crypto.getDefaultX509Alias());
        } else {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo");
        }
    }
    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    if ((certs == null || certs.length == 0 || certs[0] == null) && secretKey == null && publicKey == null
            && !kerbThumbPrint) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
    }
    if (certs != null) {
        try {
            for (int i = 0; i < certs.length; i++) {
                certs[i].checkValidity();
            }
        } catch (CertificateExpiredException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        } catch (CertificateNotYetValidException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "invalidCert", null, e);
        }
    }
    //
    // Delegate verification of a public key to a Callback Handler
    //
    if (publicKey != null) {
        PublicKeyCallback pwcb = new PublicKeyCallback(publicKey);
        try {
            Callback[] callbacks = new Callback[] { pwcb };
            cb.handle(callbacks);
            if (!pwcb.isVerified()) {
                throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, null);
            }
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION, null, null, e);
        }
    }
    try {
        boolean signatureOk = false;
        if (certs != null) {
            signatureOk = sig.checkSignatureValue(certs[0]);
        } else if (publicKey != null) {
            signatureOk = sig.checkSignatureValue(publicKey);
        } else {
            signatureOk = sig.checkSignatureValue(sig.createSecretKey(secretKey));
        }
        if (signatureOk) {
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
                tlog.debug("Verify: total= " + (t2 - t0) + ", prepare-cert= " + (t1 - t0) + ", verify= "
                        + (t2 - t1));
            }
            signatureValue[0] = sig.getSignatureValue();
            //
            // Now dig into the Signature element to get the elements that
            // this Signature covers. Build the QName of these Elements and
            // return them to caller
            //
            SignedInfo si = sig.getSignedInfo();
            int numReferences = si.getLength();
            for (int i = 0; i < numReferences; i++) {
                Reference siRef;
                try {
                    siRef = si.item(i);
                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e3);
                }
                String uri = siRef.getURI();
                if (uri != null && !"".equals(uri)) {

                    Element se = null;
                    try {
                        Transforms transforms = siRef.getTransforms();
                        for (int j = 0; j < transforms.getLength(); j++) {
                            Transform transform = transforms.item(j);
                            // We have some transforming to do before we can 
                            // determine the protected element.
                            if (STRTransform.implementedTransformURI.equals(transform.getURI())) {

                                XMLSignatureInput signatureInput = siRef.getContentsBeforeTransformation();

                                if (signatureInput.isElement()) {
                                    // The signature was already validated,
                                    // meaning that this element was already
                                    // parsed.  We can therefore be pretty
                                    // confident that this constructor will work.
                                    SecurityTokenReference secTokenRef = new SecurityTokenReference(
                                            (Element) signatureInput.getSubNode());

                                    // Use the utility to extract the element (or
                                    // generate a new one in some cases) from the
                                    // message.
                                    se = STRTransformUtil.dereferenceSTR(transform.getDocument(), secTokenRef,
                                            wsDocInfo);
                                } else {
                                    // The internal impl of Reference changed.
                                    // We expect it to return the signature input
                                    // based on a node/element.
                                    throw new WSSecurityException(WSSecurityException.FAILURE);
                                }
                            }
                        }
                    } catch (XMLSecurityException e) {
                        log.warn("Error processing signature coverage elements.", e);
                        throw new WSSecurityException(WSSecurityException.FAILURE);
                    }

                    if (se == null) {
                        se = WSSecurityUtil.getElementByWsuId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        se = WSSecurityUtil.getElementByGenId(elem.getOwnerDocument(), uri);
                    }
                    if (se == null) {
                        throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                    }
                    WSDataRef ref = new WSDataRef(uri);
                    ref.setWsuId(uri);
                    ref.setName(new QName(se.getNamespaceURI(), se.getLocalName()));
                    ref.setProtectedElement(se);
                    ref.setXpath(ReferenceListProcessor.getXPath(se));
                    ref.setAlgorithm(si.getSignatureMethodURI());
                    ref.setDigestAlgorithm(siRef.getMessageDigestAlgorithm().getAlgorithmURI());
                    protectedElements.add(ref);
                    returnElements.add(WSSecurityUtil.getIDFromReference(uri));
                } else {
                    // This is the case where the signed element is identified 
                    // by a transform such as XPath filtering
                    // We add the complete reference element to the return 
                    // elements
                    returnElements.add(siRef);
                }
            }

            // Algorithms used for signature and c14n
            signatureMethod = si.getSignatureMethodURI();
            c14nMethod = si.getCanonicalizationMethodURI();

            if (certs != null) {
                returnCert[0] = certs[0];
                if (validateCertificateChain) {
                    certificates = certs;
                }
                return certs[0].getSubjectX500Principal();
            } else if (publicKey != null) {
                return new PublicKeyPrincipal(publicKey);
            } else if (ut != null) {
                WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(ut.getName(), ut.isHashed());
                principal.setNonce(ut.getNonce());
                principal.setPassword(ut.getPassword());
                principal.setCreatedTime(ut.getCreated());
                return principal;
            } else if (dkt != null) {
                WSDerivedKeyTokenPrincipal principal = new WSDerivedKeyTokenPrincipal(dkt.getID());
                principal.setNonce(dkt.getNonce());
                principal.setLabel(dkt.getLabel());
                principal.setLength(dkt.getLength());
                principal.setOffset(dkt.getOffset());
                String basetokenId = null;
                SecurityTokenReference securityTokenReference = dkt.getSecurityTokenReference();
                if (securityTokenReference.containsReference()) {
                    basetokenId = securityTokenReference.getReference().getURI();
                    if (basetokenId.charAt(0) == '#') {
                        basetokenId = basetokenId.substring(1);
                    }
                } else {
                    // KeyIdentifier
                    basetokenId = securityTokenReference.getKeyIdentifierValue();
                }
                principal.setBasetokenId(basetokenId);
                return principal;
            } else if (samlKi != null) {
                final SAMLAssertion assertion = samlKi.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getId());
                principal.setTokenObject(assertion);
                return principal;

            } else if (saml2Ki != null) {
                Assertion assertion = saml2Ki.getAssertion();
                CustomTokenPrincipal principal = new CustomTokenPrincipal(assertion.getID());
                principal.setTokenObject(assertion);
                return principal;
            } else if (secretKey != null) {
                // This is the custom key scenario
                CustomTokenPrincipal principal = new CustomTokenPrincipal(customTokenId);
                return principal;
            } else {
                throw new WSSecurityException("Cannot determine principal");
            }
        } else {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
    } catch (XMLSignatureException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1);
    }
}