Example usage for javax.xml.namespace QName equals

List of usage examples for javax.xml.namespace QName equals

Introduction

In this page you can find the example usage for javax.xml.namespace QName equals.

Prototype

public final boolean equals(Object objectToTest) 

Source Link

Document

Test this QName for equality with another Object.

If the Object to be tested is not a QName or is null, then this method returns false.

Two QNames are considered equal if and only if both the Namespace URI and local part are equal.

Usage

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 www  .  ja  va  2 s.com
    } 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.token.BinarySecurity.java

/**
 * Constructor./*from  ww w .ja v a  2 s .  c o m*/
 * 
 * @param elem 
 * @throws WSSecurityException 
 */
public BinarySecurity(Element elem) throws WSSecurityException {
    this.element = elem;
    QName el = new QName(this.element.getNamespaceURI(), this.element.getLocalName());
    if (!el.equals(TOKEN_BST) && !el.equals(TOKEN_KI)) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType",
                new Object[] { el });
    }
    String encoding = getEncodingType();
    //
    // if the Element is a BinarySecurityToken then
    //     encoding may be null -> default is Base64
    //     if encoding is not null and not empty it must be Base64
    // else
    //     this is a keyidentifier element
    //     must contain an encoding attribute which must be Base64
    //     in this case
    //
    if (el.equals(TOKEN_BST)) {
        if (encoding != null && encoding.length() > 0 && !encoding.equals(BASE64_ENCODING)) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badEncoding",
                    new Object[] { encoding });
        }
    } else if (el.equals(TOKEN_KI) && !BASE64_ENCODING.equals(encoding)) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badEncoding",
                new Object[] { encoding });
    }
}

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

/**
 * This will create a DerivedKeyToken object with the given DerivedKeyToken element
 *
 * @param elem The DerivedKeyToken DOM element
 * @throws WSSecurityException If the element is not a derived key token
 *///from w w w . j  a  v  a2 s  .c o  m
public DerivedKeyToken(Element elem) throws WSSecurityException {
    log.debug("DerivedKeyToken: created : element constructor");
    this.element = elem;
    QName el = new QName(this.element.getNamespaceURI(), this.element.getLocalName());

    if (!(el.equals(ConversationConstants.DERIVED_KEY_TOKEN_QNAME_05_02)
            || el.equals(ConversationConstants.DERIVED_KEY_TOKEN_QNAME_05_12))) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
                new Object[] { el });
    }
    this.elementSecurityTokenReference = (Element) WSSecurityUtil.getDirectChild(this.element,
            ConversationConstants.SECURITY_TOKEN_REFERENCE_LN, WSConstants.WSSE_NS);

    this.ns = el.getNamespaceURI();

    this.elementProperties = (Element) WSSecurityUtil.getDirectChild(this.element,
            ConversationConstants.PROPERTIES_LN, this.ns);
    this.elementGeneration = (Element) WSSecurityUtil.getDirectChild(this.element,
            ConversationConstants.GENERATION_LN, this.ns);
    this.elementOffset = (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.OFFSET_LN,
            this.ns);
    this.elementLength = (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.LENGTH_LN,
            this.ns);
    this.elementLabel = (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.LABEL_LN,
            this.ns);
    this.elementNonce = (Element) WSSecurityUtil.getDirectChild(this.element, ConversationConstants.NONCE_LN,
            this.ns);
}

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

/**
 * Constructs a <code>UsernameToken</code> object and parses the
 * <code>wsse:UsernameToken</code> element to initialize it.
 * //from  w ww. j  a  v a  2  s . c o m
 * @param elem the <code>wsse:UsernameToken</code> element that contains
 *             the UsernameToken data
 * @param allowNamespaceQualifiedPasswordTypes whether to allow (wsse)
 *        namespace qualified password types or not (for interop with WCF)
 * @throws WSSecurityException
 */
public UsernameToken(Element elem, boolean allowNamespaceQualifiedPasswordTypes) throws WSSecurityException {
    element = elem;
    QName el = new QName(element.getNamespaceURI(), element.getLocalName());
    if (!el.equals(TOKEN)) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType00",
                new Object[] { el });
    }
    elementUsername = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.USERNAME_LN,
            WSConstants.WSSE_NS);
    elementPassword = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.PASSWORD_LN,
            WSConstants.WSSE_NS);
    elementNonce = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.NONCE_LN, WSConstants.WSSE_NS);
    elementCreated = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.CREATED_LN,
            WSConstants.WSU_NS);
    elementSalt = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.SALT_LN, WSConstants.WSSE11_NS);
    elementIteration = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.ITERATION_LN,
            WSConstants.WSSE11_NS);
    if (elementUsername == null) {
        throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType01",
                new Object[] { el });
    }
    hashed = false;
    if (elementSalt != null) {
        //
        // If the UsernameToken is to be used for key derivation, the (1.1)
        // spec says that it cannot contain a password, and it must contain
        // an Iteration element
        //
        if (elementPassword != null || elementIteration == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType01",
                    new Object[] { el });
        }
        return;
    }
    if (elementPassword != null) {
        if (elementPassword.hasAttribute(WSConstants.PASSWORD_TYPE_ATTR)) {
            passwordType = elementPassword.getAttribute(WSConstants.PASSWORD_TYPE_ATTR);
        } else if (elementPassword.hasAttributeNS(WSConstants.WSSE_NS, WSConstants.PASSWORD_TYPE_ATTR)) {
            if (allowNamespaceQualifiedPasswordTypes) {
                passwordType = elementPassword.getAttributeNS(WSConstants.WSSE_NS,
                        WSConstants.PASSWORD_TYPE_ATTR);
            } else {
                throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType01",
                        new Object[] { el });
            }
        }

    }
    if (passwordType != null && passwordType.equals(WSConstants.PASSWORD_DIGEST)) {
        hashed = true;
        if (elementNonce == null || elementCreated == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType01",
                    new Object[] { el });
        }
    }
}

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   ww w  .  j  a va 2 s. c om*/
    // 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 ww. j a v  a  2 s.c  o  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);
    }
}

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 {/*w  w w.  ja va 2s . com*/
            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.str.EncryptedKeySTRParser.java

/**
 * Parse a SecurityTokenReference element and extract credentials.
 * /*from  www  . j  a  va 2  s  .c om*/
 * @param strElement The SecurityTokenReference element
 * @param data the RequestData associated with the request
 * @param wsDocInfo The WSDocInfo object to access previous processing results
 * @param parameters A set of implementation-specific parameters
 * @throws WSSecurityException
 */
public void parseSecurityTokenReference(Element strElement, RequestData data, WSDocInfo wsDocInfo,
        Map<String, Object> parameters) throws WSSecurityException {
    Crypto crypto = data.getDecCrypto();
    WSSConfig config = data.getWssConfig();
    boolean bspCompliant = true;
    if (config != null) {
        bspCompliant = config.isWsiBSPCompliant();
    }

    SecurityTokenReference secRef = new SecurityTokenReference(strElement, bspCompliant);

    String uri = null;
    if (secRef.containsReference()) {
        uri = secRef.getReference().getURI();
        if (uri.charAt(0) == '#') {
            uri = uri.substring(1);
        }
        referenceType = REFERENCE_TYPE.DIRECT_REF;
    } else if (secRef.containsKeyIdentifier()) {
        uri = secRef.getKeyIdentifierValue();
        if (SecurityTokenReference.THUMB_URI.equals(secRef.getKeyIdentifierValueType())) {
            referenceType = REFERENCE_TYPE.THUMBPRINT_SHA1;
        } else {
            referenceType = REFERENCE_TYPE.KEY_IDENTIFIER;
        }
    }

    WSSecurityEngineResult result = wsDocInfo.getResult(uri);
    if (result != null) {
        processPreviousResult(result, secRef, data, wsDocInfo, bspCompliant);
    } else if (secRef.containsKeyIdentifier()) {
        if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())
                || WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
            AssertionWrapper assertion = SAMLUtil.getAssertionFromKeyIdentifier(secRef, strElement, data,
                    wsDocInfo);
            if (bspCompliant) {
                BSPEnforcer.checkSamlTokenBSPCompliance(secRef, assertion);
            }
            SAMLKeyInfo samlKi = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo, bspCompliant);
            certs = samlKi.getCerts();
        } else {
            if (bspCompliant) {
                BSPEnforcer.checkBinarySecurityBSPCompliance(secRef, null);
            }
            certs = secRef.getKeyIdentifier(crypto);
        }
    } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
        referenceType = REFERENCE_TYPE.ISSUER_SERIAL;
        certs = secRef.getX509IssuerSerial(crypto);
    } else if (secRef.containsReference()) {
        Element bstElement = secRef.getTokenElement(strElement.getOwnerDocument(), wsDocInfo,
                data.getCallbackHandler());

        // at this point ... check token type: Binary
        QName el = new QName(bstElement.getNamespaceURI(), bstElement.getLocalName());
        if (el.equals(WSSecurityEngine.BINARY_TOKEN)) {
            X509Security token = new X509Security(bstElement);
            if (bspCompliant) {
                BSPEnforcer.checkBinarySecurityBSPCompliance(secRef, token);
            }
            certs = new X509Certificate[] { token.getX509Certificate(crypto) };
        } else {
            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                    "unsupportedBinaryTokenType", null);
        }
    }

    if (LOG.isDebugEnabled() && certs != null && certs[0] != null) {
        LOG.debug("cert: " + certs[0]);
    }
}

From source file:org.apereo.portal.portlet.container.EventProviderImpl.java

private boolean isDeclaredAsPublishingEvent(QName qname) {
    final PortletDefinition portletDescriptor = this.portletWindow.getPlutoPortletWindow()
            .getPortletDefinition();/*  www.  j a  v a2s.  co  m*/
    final List<? extends EventDefinitionReference> events = portletDescriptor.getSupportedPublishingEvents();

    if (events == null) {
        return false;
    }

    final PortletApplicationDefinition application = portletDescriptor.getApplication();
    final String defaultNamespace = application.getDefaultNamespace();
    for (final EventDefinitionReference ref : events) {
        final QName name = ref.getQualifiedName(defaultNamespace);
        if (name == null) {
            continue;
        }
        if (qname.equals(name)) {
            return true;
        }
    }
    return false;
}

From source file:org.apereo.portal.portlet.container.EventProviderImpl.java

private boolean isValueInstanceOfDefinedClass(QName qname, Serializable value) {
    final PortletDefinition portletDefinition = this.portletWindow.getPlutoPortletWindow()
            .getPortletDefinition();/*from w w  w  . java  2s.  co  m*/
    final PortletApplicationDefinition app = portletDefinition.getApplication();
    final List<? extends EventDefinition> events = app.getEventDefinitions();
    if (events == null) {
        return true;
    }

    final String defaultNamespace = app.getDefaultNamespace();

    for (final EventDefinition eventDefinition : events) {
        if (eventDefinition.getQName() != null) {
            if (eventDefinition.getQName().equals(qname)) {
                final Class<? extends Serializable> valueClass = value.getClass();
                return valueClass.getName().equals(eventDefinition.getValueType());
            }
        } else {
            final QName tmp = new QName(defaultNamespace, eventDefinition.getName());
            if (tmp.equals(qname)) {
                final Class<? extends Serializable> valueClass = value.getClass();
                return valueClass.getName().equals(eventDefinition.getValueType());
            }
        }
    }

    // event not declared
    return true;
}