Example usage for org.w3c.dom Node getNamespaceURI

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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.ws.security.message.WSSecSignature.java

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;/*w w  w .  j a  va  2s . c o 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 
 *///w ww  .ja  v  a  2 s. co m
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();
    }//from  w w  w  .  j  a v  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.ReferenceListProcessor.java

/**
 * Dereferences and decodes encrypted data elements.
 * /*from  w w  w .jav a2 s. c om*/
 * @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//from  w w  w  .  ja  va 2s  . 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 {/*from ww w. j  a  va2  s .  co  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 " });

    }

}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the first element that matches <code>name</code> and
 * <code>namespace</code>. <p/> This is a replacement for a XPath lookup
 * <code>//name</code> with the given namespace. It's somewhat faster than
 * XPath, and we do not deal with prefixes, just with the real namespace URI
 * //from  w ww  .  ja  v  a  2s. c om
 * @param startNode Where to start the search
 * @param name Local name of the element
 * @param namespace Namespace URI of the element
 * @return The found element or <code>null</code>
 */
public static Node findElement(Node startNode, String name, String namespace) {
    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE && startNode.getLocalName().equals(name)) {
            String ns = startNode.getNamespaceURI();
            if (ns != null && ns.equals(namespace)) {
                return startNode;
            }

            if ((namespace == null || namespace.length() == 0) && (ns == null || ns.length() == 0)) {
                return startNode;
            }
        }
        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return null;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return null;
}

From source file:org.apache.ws.security.WSSecurityEngine.java

/**
 * Process the security header given the <code>wsse:Security</code> DOM
 * Element. //from w ww  . ja  va2  s. c o  m
 * 
 * This function loops over all direct child elements of the
 * <code>wsse:Security</code> header. If it finds a known element, it
 * transfers control to the appropriate handling function. The method
 * processes the known child elements in the same order as they appear in
 * the <code>wsse:Security</code> element. This is in accordance to the WS
 * Security specification. <p/>
 * 
 * Currently the functions can handle the following child elements:
 * 
 * <ul>
 * <li>{@link #SIGNATURE <code>ds:Signature</code>}</li>
 * <li>{@link #ENCRYPTED_KEY <code>xenc:EncryptedKey</code>}</li>
 * <li>{@link #REFERENCE_LIST <code>xenc:ReferenceList</code>}</li>
 * <li>{@link #usernameToken <code>wsse:UsernameToken</code>}</li>
 * <li>{@link #timeStamp <code>wsu:Timestamp</code>}</li>
 * </ul>
 *
 * Note that additional child elements can be processed if appropriate
 * Processors have been registered with the WSSCondig instance set
 * on this class.
 *
 * @param securityHeader the <code>wsse:Security</code> header element
 * @param cb             a callback hander to the caller to resolve passwords during
 *                       encryption and {@link UsernameToken}handling
 * @param sigCrypto      the object that implements the access to the keystore and the
 *                       handling of certificates used for Signature
 * @param decCrypto      the object that implements the access to the keystore and the
 *                       handling of certificates used for Decryption
 * @return a Vector of {@link WSSecurityEngineResult}. Each element in the
 *         the Vector represents the result of a security action. The elements
 *         are ordered according to the sequence of the security actions in the
 *         wsse:Signature header. The Vector maybe empty if no security processing
 *         was performed.
 * @throws WSSecurityException
 */
protected Vector processSecurityHeader(Element securityHeader, CallbackHandler cb, Crypto sigCrypto,
        Crypto decCrypto) throws WSSecurityException {

    long t0 = 0, t1 = 0, t2 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    /*
     * Gather some info about the document to process and store
     * it for retrieval. Store the implementation of signature crypto
     * (no need for encryption --- yet)
     */
    WSDocInfo wsDocInfo = new WSDocInfo(securityHeader.getOwnerDocument());
    wsDocInfo.setCrypto(sigCrypto);

    NodeList list = securityHeader.getChildNodes();
    int len = list.getLength();
    Node elem;
    if (tlog.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    Vector returnResults = new Vector();

    for (int i = 0; i < len; i++) {
        elem = list.item(i);
        if (elem.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        QName el = new QName(elem.getNamespaceURI(), elem.getLocalName());
        final WSSConfig cfg = getWssConfig();
        Processor p = cfg.getProcessor(el);
        /*
         * Call the processor for this token. After the processor returns, 
         * store it for later retrieval. The token processor may store some
         * information about the processed token
         */
        if (p != null) {
            p.handleToken((Element) elem, sigCrypto, decCrypto, cb, wsDocInfo, returnResults, cfg);
            wsDocInfo.setProcessor(p);
        } else {
            /*
             * Add check for a BinarySecurityToken, add info to WSDocInfo. If BST is
             * found before a Signature token this would speed up (at least a little
             * bit) the processing of STR Transform.
             */
            if (doDebug) {
                log.debug("Unknown Element: " + elem.getLocalName() + " " + elem.getNamespaceURI());
            }
        }
    }
    if (tlog.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
        tlog.debug("processHeader: total " + (t2 - t0) + ", prepare " + (t1 - t0) + ", handle " + (t2 - t1));
    }
    return returnResults;
}

From source file:org.apache.xml.security.keys.content.X509Data.java

/**
 * Method lengthUnknownElement/*w  ww  . j  av  a  2  s  .c  o m*/
 *
 * @return the number of UnknownElement elements in this X509Data
 */
public int lengthUnknownElement() {
    int result = 0;
    Node n = this.constructionElement.getFirstChild();
    while (n != null) {
        if ((n.getNodeType() == Node.ELEMENT_NODE) && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
            result++;
        }
        n = n.getNextSibling();
    }

    return result;
}

From source file:org.apache.xml.security.keys.KeyInfo.java

/**
 * Method lengthUnknownElement// w  w  w  .  jav  a2 s . c  o m
 * NOTE possibly buggy.
 * @return the number of the UnknownElement tags
 */
public int lengthUnknownElement() {
    int res = 0;
    NodeList nl = this.constructionElement.getChildNodes();

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);

        /**
         * $todo$ using this method, we don't see unknown Elements
         *  from Signature NS; revisit
         */
        if ((current.getNodeType() == Node.ELEMENT_NODE)
                && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
            res++;
        }
    }

    return res;
}