Example usage for org.w3c.dom Node getLocalName

List of usage examples for org.w3c.dom Node getLocalName

Introduction

In this page you can find the example usage for org.w3c.dom Node getLocalName.

Prototype

public String getLocalName();

Source Link

Document

Returns the local part of the qualified name of this node.

Usage

From source file:org.apache.syncope.core.logic.SAML2IdPLogic.java

private List<SAML2IdPTO> importIdPs(final InputStream input) throws Exception {
    List<EntityDescriptor> idpEntityDescriptors = new ArrayList<>();

    Element root = OpenSAMLUtil.getParserPool().parse(new InputStreamReader(input)).getDocumentElement();
    if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom(root));
    } else if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (SAMLConstants.SAML20MD_NS.equals(child.getNamespaceURI())
                    && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(child.getLocalName())) {

                NodeList descendants = child.getChildNodes();
                for (int j = 0; j < descendants.getLength(); j++) {
                    Node descendant = descendants.item(j);
                    if (SAMLConstants.SAML20MD_NS.equals(descendant.getNamespaceURI())
                            && IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(descendant.getLocalName())) {

                        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom((Element) child));
                    }/*w w w.j a  va2s.co m*/
                }
            }
        }
    }

    List<SAML2IdPTO> result = new ArrayList<>(idpEntityDescriptors.size());
    for (EntityDescriptor idpEntityDescriptor : idpEntityDescriptors) {
        SAML2IdPTO idpTO = new SAML2IdPTO();
        idpTO.setEntityID(idpEntityDescriptor.getEntityID());
        idpTO.setName(idpEntityDescriptor.getEntityID());
        idpTO.setUseDeflateEncoding(false);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            saml2rw.write(new OutputStreamWriter(baos), idpEntityDescriptor, false);
            idpTO.setMetadata(Base64.getEncoder().encodeToString(baos.toByteArray()));
        }

        ItemTO connObjectKeyItem = new ItemTO();
        connObjectKeyItem.setIntAttrName("username");
        connObjectKeyItem.setExtAttrName("NameID");
        idpTO.setConnObjectKeyItem(connObjectKeyItem);

        SAML2IdPEntity idp = cache.put(idpEntityDescriptor, idpTO);
        if (idp.getSSOLocation(SAML2BindingType.POST) != null) {
            idpTO.setBindingType(SAML2BindingType.POST);
        } else if (idp.getSSOLocation(SAML2BindingType.REDIRECT) != null) {
            idpTO.setBindingType(SAML2BindingType.REDIRECT);
        } else {
            throw new IllegalArgumentException(
                    "Neither POST nor REDIRECT artifacts supported by " + idp.getId());
        }

        result.add(idpTO);
    }

    return result;
}

From source file:org.apache.ws.scout.transport.SaajTransport.java

private Element getFirstChildElement(Element el, String tagName) {
    Element childEl = null;/*w ww  .ja v a  2s.co m*/
    NodeList nlist = el != null ? el.getChildNodes() : null;
    int len = nlist != null ? nlist.getLength() : 0;
    for (int i = 0; childEl == null && i < len; i++) {
        Node node = nlist.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (tagName == null || tagName.equals(node.getLocalName()))
                childEl = (Element) node;
        }
    }
    if (log.isDebugEnabled()) {
        String responseObtained = XMLUtils.convertNodeToXMLString(childEl);
        log.debug("Response obtained: %s" + responseObtained);
    }
    return childEl;
}

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

/**
 * Method length./*from w  w w  . j  a v  a 2 s  .  c o  m*/
 * 
 * @param namespace
 * @param localname
 * @return number of elements with matching localname and namespace
 */
public int length(String namespace, String localname) {
    NodeList childNodes = this.element.getChildNodes();
    int result = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node n = childNodes.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            String ns = n.getNamespaceURI();
            String name = n.getLocalName();
            if ((((namespace != null) && namespace.equals(ns)) || ((namespace == null) && (ns == null)))
                    && (localname.equals(name))) {
                result++;
            }
        }
    }
    return result;
}

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

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;//from w  ww .j a v  a 2 s.  c om
    NamedNodeMap attributes;
    Node attribute;
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible == true) {
        attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

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

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;//from   w w w . jav  a 2s .  co  m
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible == true) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

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

/**
 * Get the List of inclusive prefixes from the DOM Element argument 
 *//*from w w  w . j a va2 s  .  com*/
public List<String> getInclusivePrefixes(Element target, boolean excludeVisible) {
    List<String> result = new ArrayList<String>();
    Node parent = target;
    while (parent.getParentNode() != null && !(Node.DOCUMENT_NODE == parent.getParentNode().getNodeType())) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

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 .ja  v a 2  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.ReferenceListProcessor.java

/**
 * Dereferences and decodes encrypted data elements.
 * /*w w  w  . j  a  v  a 2  s.  c  o m*/
 * @param elem contains the <code>ReferenceList</code> to the encrypted
 *             data elements
 * @param cb the callback handler to get the key for a key name stored if
 *           <code>KeyInfo</code> inside the encrypted data elements
 */
private ArrayList handleReferenceList(Element elem, CallbackHandler cb, Crypto crypto)
        throws WSSecurityException {
    Node tmpE = null;
    ArrayList dataRefUris = new ArrayList();
    for (tmpE = elem.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 = decryptDataRefEmbedded(elem.getOwnerDocument(), dataRefURI, cb, crypto);
            dataRefUris.add(dataRef);
        }
    }

    return dataRefUris;
}

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

/**
 * Decrypt the EncryptedData argument using a SecretKey.
 * @param doc The (document) owner of EncryptedData
 * @param dataRefURI The URI of EncryptedData
 * @param encData The EncryptedData element
 * @param symmetricKey The SecretKey with which to decrypt EncryptedData
 * @param symEncAlgo The symmetric encryption algorithm to use
 * @throws WSSecurityException/* w ww .jav a2 s. c o m*/
 */
public static WSDataRef decryptEncryptedData(Document doc, String dataRefURI, Element encData,
        SecretKey symmetricKey, String symEncAlgo) throws WSSecurityException {
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }

    WSDataRef dataRef = new WSDataRef(dataRefURI);
    dataRef.setWsuId(dataRefURI);
    dataRef.setAlgorithm(symEncAlgo);
    boolean content = X509Util.isContent(encData);
    dataRef.setContent(content);

    Node parent = encData.getParentNode();
    Node previousSibling = encData.getPreviousSibling();
    if (content) {
        encData = (Element) encData.getParentNode();
        parent = encData.getParentNode();
    }

    try {
        xmlCipher.doFinal(doc, encData, content);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
    }

    if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
            && parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {

        Node decryptedHeader = parent.getFirstChild();
        Element decryptedHeaderClone = (Element) decryptedHeader.cloneNode(true);
        parent.getParentNode().appendChild(decryptedHeaderClone);
        parent.getParentNode().removeChild(parent);
        dataRef.setProtectedElement(decryptedHeaderClone);
        dataRef.setXpath(getXPath(decryptedHeaderClone));
    } else if (content) {
        dataRef.setProtectedElement(encData);
        dataRef.setXpath(getXPath(encData));
    } else {
        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(getXPath(decryptedNode));
    }

    return dataRef;
}

From source file:org.apache.ws.security.saml.SAMLUtil.java

public static SAMLKeyInfo getSAMLKeyInfo(SAMLAssertion assertion, Crypto crypto, CallbackHandler cb)
        throws WSSecurityException {

    //First ask the cb whether it can provide the secret
    WSPasswordCallback pwcb = new WSPasswordCallback(assertion.getId(), WSPasswordCallback.CUSTOM_TOKEN);
    if (cb != null) {
        try {/*  ww  w.  j a  v  a  2 s.  c  o  m*/
            cb.handle(new Callback[] { pwcb });
        } catch (Exception e1) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKey",
                    new Object[] { assertion.getId() }, e1);
        }
    }

    byte[] key = pwcb.getKey();

    if (key != null) {
        return new SAMLKeyInfo(assertion, key);
    } else {
        Iterator statements = assertion.getStatements();
        while (statements.hasNext()) {
            SAMLStatement stmt = (SAMLStatement) statements.next();
            if (stmt instanceof SAMLAttributeStatement) {
                SAMLAttributeStatement attrStmt = (SAMLAttributeStatement) stmt;
                SAMLSubject samlSubject = attrStmt.getSubject();
                Element kiElem = samlSubject.getKeyInfo();

                NodeList children = kiElem.getChildNodes();
                int len = children.getLength();

                for (int i = 0; i < len; i++) {
                    Node child = children.item(i);
                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    QName el = new QName(child.getNamespaceURI(), child.getLocalName());
                    if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)) {

                        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
                        proc.handleEncryptedKey((Element) child, cb, crypto, null);

                        return new SAMLKeyInfo(assertion, proc.getDecryptedBytes());
                    } else if (el.equals(new QName(WSConstants.WST_NS, "BinarySecret"))) {
                        Text txt = (Text) child.getFirstChild();
                        return new SAMLKeyInfo(assertion, Base64.decode(txt.getData()));
                    }
                }

            } else if (stmt instanceof SAMLAuthenticationStatement) {
                SAMLAuthenticationStatement authStmt = (SAMLAuthenticationStatement) stmt;
                SAMLSubject samlSubj = authStmt.getSubject();
                if (samlSubj == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLToken",
                            new Object[] { "for Signature (no Subject)" });
                }

                Element e = samlSubj.getKeyInfo();
                X509Certificate[] certs = null;
                try {
                    KeyInfo ki = new KeyInfo(e, null);

                    if (ki.containsX509Data()) {
                        X509Data data = ki.itemX509Data(0);
                        XMLX509Certificate certElem = null;
                        if (data != null && data.containsCertificate()) {
                            certElem = data.itemCertificate(0);
                        }
                        if (certElem != null) {
                            X509Certificate cert = certElem.getX509Certificate();
                            certs = new X509Certificate[1];
                            certs[0] = cert;
                            return new SAMLKeyInfo(assertion, certs);
                        }
                    }

                } catch (XMLSecurityException e3) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                            new Object[] { "cannot get certificate (key holder)" }, e3);
                }

            } else {
                throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                        new Object[] { "cannot get certificate or key " });
            }
        }

        throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLSecurity",
                new Object[] { "cannot get certificate or key " });

    }

}