You are viewing a plain text version of this content. The canonical link for it is here.
Posted to fx-dev@ws.apache.org by di...@apache.org on 2005/09/14 06:08:38 UTC

svn commit: r280758 [2/2] - in /webservices/wss4j/trunk: ./ src/org/apache/ws/security/ src/org/apache/ws/security/processor/

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/SignatureProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/SignatureProcessor.java?rev=280758&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/SignatureProcessor.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/SignatureProcessor.java Tue Sep 13 21:08:31 2005
@@ -0,0 +1,361 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.processor;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSDocInfoStore;
+import org.apache.ws.security.WSSecurityEngine;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.WSUsernameTokenPrincipal;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.EnvelopeIdResolver;
+import org.apache.ws.security.message.token.BinarySecurity;
+import org.apache.ws.security.message.token.PKIPathSecurity;
+import org.apache.ws.security.message.token.SecurityTokenReference;
+import org.apache.ws.security.message.token.UsernameToken;
+import org.apache.ws.security.message.token.X509Security;
+import org.apache.ws.security.saml.SAMLUtil;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+
+import org.apache.xml.security.keys.KeyInfo;
+import org.apache.xml.security.signature.Reference;
+import org.apache.xml.security.signature.SignedInfo;
+import org.apache.xml.security.signature.XMLSignature;
+import org.apache.xml.security.signature.XMLSignatureException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import javax.xml.namespace.QName;
+import javax.security.auth.callback.CallbackHandler;
+import java.security.Principal;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.X509Certificate;
+import java.util.Vector;
+
+public class SignatureProcessor implements Processor {
+    private static Log log = LogFactory.getLog(SignatureProcessor.class.getName());
+    private static Log tlog =
+            LogFactory.getLog("org.apache.ws.security.TIME");
+
+    public void handleToken(Element elem, Crypto crypto, Crypto decCrypto, CallbackHandler cb, WSDocInfo wsDocInfo, Vector returnResults) throws WSSecurityException {
+        if (log.isDebugEnabled()) {
+            log.debug("Found signature element");
+        }
+        WSDocInfoStore.store(wsDocInfo);
+        X509Certificate[] returnCert = new X509Certificate[1];
+        Vector returnQname[] = new Vector[1];
+        byte[][] signatureValue = new byte[1][];
+        Principal lastPrincipalFound = null;
+        try {
+            lastPrincipalFound = verifyXMLSignature((Element) elem,
+                    crypto, returnCert, returnQname, signatureValue);
+        } catch (WSSecurityException ex) {
+            throw ex;
+        } finally {
+            WSDocInfoStore.delete(wsDocInfo);
+        }
+        if (lastPrincipalFound instanceof WSUsernameTokenPrincipal) {
+            returnResults.add(0, new WSSecurityEngineResult(
+                    WSConstants.UT_SIGN, lastPrincipalFound, null,
+                    returnQname[0], signatureValue[0]));
+
+        } else {
+            returnResults.add(0, new WSSecurityEngineResult(
+                    WSConstants.SIGN, lastPrincipalFound,
+                    returnCert[0], returnQname[0], signatureValue[0]));
+        }
+    }
+
+    /**
+     * Verify the WS-Security signature.
+     * <p/>
+     * 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.
+     * <p/>
+     * 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 derefenced 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>
+     * <p/>
+     * The methods checks is the certificate is valid and calls the
+     * {@link org.apache.xml.security.signature.XMLSignature#checkSignatureValue(X509Certificate) verfication} 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. Ther caller may then further validate
+     *                    the certificate
+     * @param returnQname verifyXMLSignature store the Qnames of all signed elements
+     *                    in this Vector ordered according the sequence in the Signature
+     *                    header.
+     * @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,
+                                           Vector[] returnQname,
+                                           byte[][] signatureValue)
+            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");
+        }
+
+        sig.addResourceResolver(EnvelopeIdResolver.getInstance());
+
+        X509Certificate[] certs = null;
+        KeyInfo info = sig.getKeyInfo();
+        byte[] secretKey = null;
+        UsernameToken ut = null;
+
+        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);
+
+            int docHash = elem.getOwnerDocument().hashCode();
+            /*
+                * Her we get some information about the document that is being
+                * processed, in partucular the crypto implementation, and already
+                * detected BST that may be used later during dereferencing.
+                */
+            WSDocInfo wsDocInfo = WSDocInfoStore.lookup(docHash);
+
+            if (secRef.containsReference()) {
+                Element token = secRef.getTokenElement(elem.getOwnerDocument(),
+                        wsDocInfo);
+                /*
+                     * at this point check token type: UsernameToken, Binary, SAML
+                     * Crypto required only for Binary and SAML
+                     */
+                QName el = new QName(token.getNamespaceURI(), token
+                        .getLocalName());
+                if (el.equals(WSSecurityEngine.usernameToken)) {
+                    ut = new UsernameToken(token);
+                    secretKey = ut.getSecretKey();
+                } else {
+                    if (crypto == null) {
+                        throw new WSSecurityException(WSSecurityException.FAILURE,
+                                "noSigCryptoFile");
+                    }
+                    if (el.equals(WSSecurityEngine.binaryToken)) {
+                        certs = getCertificatesTokenReference((Element) token,
+                                crypto);
+                    } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
+                        certs = SAMLUtil.getCertificatesFromSAML((Element) token);
+                    } else {
+                        throw new WSSecurityException(
+                                WSSecurityException.INVALID_SECURITY,
+                                "unsupportedKeyInfo", new Object[]{el
+                                .toString()});
+                    }
+                }
+            } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
+                certs = secRef.getX509IssuerSerial(crypto);
+            } else if (secRef.containsKeyIdentifier()) {
+                certs = secRef.getKeyIdentifier(crypto);
+            } 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) {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
+        }
+        if (certs != null) {
+            try {
+                certs[0].checkValidity();
+            } catch (CertificateExpiredException e) {
+                throw new WSSecurityException(WSSecurityException.FAILED_CHECK,
+                        "invalidCert");
+            } catch (CertificateNotYetValidException e) {
+                throw new WSSecurityException(WSSecurityException.FAILED_CHECK,
+                        "invalidCert");
+            }
+        }
+        try {
+            boolean signatureOk = false;
+            if (certs != null) {
+                signatureOk = sig.checkSignatureValue(certs[0]);
+            } 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();
+                Vector qvec = new Vector(numReferences);
+                for (int i = 0; i < numReferences; i++) {
+                    Reference siRef;
+                    try {
+                        siRef = si.item(i);
+                    } catch (XMLSecurityException e3) {
+                        throw new WSSecurityException(
+                                WSSecurityException.FAILED_CHECK);
+                    }
+                    String uri = siRef.getURI();
+                    Element se = WSSecurityUtil.getElementByWsuId(elem.getOwnerDocument(), uri);
+                    if (se == null) {
+                        se = WSSecurityUtil.getElementByGenId(elem
+                                .getOwnerDocument(), uri);
+                    }
+                    if (se == null) {
+                        throw new WSSecurityException(
+                                WSSecurityException.FAILED_CHECK);
+                    }
+                    QName qn = new QName(se.getNamespaceURI(), se
+                            .getLocalName());
+                    qvec.add(qn);
+                }
+                returnQname[0] = qvec;
+                if (certs != null) {
+                    returnCert[0] = certs[0];
+                    return certs[0].getSubjectDN();
+                } else {
+                    WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(
+                            ut.getName(), ut.isHashed());
+                    principal.setNonce(ut.getNonce());
+                    principal.setPassword(ut.getPassword());
+                    principal.setCreatedTime(ut.getCreated());
+                    return principal;
+                }
+            } else {
+                throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
+            }
+        } catch (XMLSignatureException e1) {
+            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
+        }
+    }
+
+    /**
+     * Extracts the certificate(s) from the Binary Security token reference.
+     * <p/>
+     *
+     * @param elem The element containing the binary security token. This is
+     *             either X509 certificate(s) or a PKIPath.
+     * @return an array of X509 certificates
+     * @throws WSSecurityException
+     */
+    public X509Certificate[] getCertificatesTokenReference(Element elem,
+                                                           Crypto crypto)
+            throws WSSecurityException {
+        BinarySecurity token = createSecurityToken(elem);
+        if (token instanceof PKIPathSecurity) {
+            return ((PKIPathSecurity) token).getX509Certificates(false, crypto);
+        } else if (token instanceof X509Security) {
+            X509Certificate cert = ((X509Security) token).getX509Certificate(crypto);
+            X509Certificate[] certs = new X509Certificate[1];
+            certs[0] = cert;
+            return certs;
+        }
+        return null;
+    }
+
+    /**
+     * Checks the <code>element</code> and creates appropriate binary security object.
+     *
+     * @param element The XML element that contains either a <code>BinarySecurityToken
+     *                </code> or a <code>PKIPath</code> element. Other element types a not
+     *                supported
+     * @return the BinarySecurity object, either a <code>X509Security</code> or a
+     *         <code>PKIPathSecurity</code> object.
+     * @throws WSSecurityException
+     */
+    private BinarySecurity createSecurityToken(Element element) throws WSSecurityException {
+        BinarySecurity token = new BinarySecurity(element);
+        String type = token.getValueType();
+        X509Security x509 = null;
+        PKIPathSecurity pkiPath = null;
+
+        if (X509Security.getType().equals(type)) {
+            x509 = new X509Security(element);
+            return (BinarySecurity) x509;
+        } else if (PKIPathSecurity.getType().equals(type)) {
+            pkiPath = new PKIPathSecurity(element);
+            return (BinarySecurity) pkiPath;
+        }
+        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
+                "unsupportedBinaryTokenType", new Object[]{type});
+    }
+
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/TimestampProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/TimestampProcessor.java?rev=280758&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/TimestampProcessor.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/TimestampProcessor.java Tue Sep 13 21:08:31 2005
@@ -0,0 +1,72 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.processor;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.token.Timestamp;
+import org.apache.ws.security.util.XmlSchemaDateFormat;
+import org.w3c.dom.Element;
+
+import javax.security.auth.callback.CallbackHandler;
+import java.text.DateFormat;
+import java.util.Calendar;
+import java.util.Vector;
+
+public class TimestampProcessor implements Processor {
+    private static Log log = LogFactory.getLog(TimestampProcessor.class.getName());
+
+    public void handleToken(Element elem, Crypto crypto, Crypto decCrypto, CallbackHandler cb, WSDocInfo wsDocInfo, Vector returnResults) throws WSSecurityException {
+        if (log.isDebugEnabled()) {
+            log.debug("Found Timestamp list element");
+        }
+        /*
+         * Decode Timestamp, add the found time (created/expiry) to result
+         */
+        Timestamp timestamp = new Timestamp((Element) elem);
+        handleTimestamp(timestamp);
+        returnResults.add(0,
+                new WSSecurityEngineResult(WSConstants.TS,
+                        timestamp));
+    }
+
+    public void handleTimestamp(Timestamp timestamp) throws WSSecurityException {
+        if (log.isDebugEnabled()) {
+            log.debug("Preparing to verify the timestamp");
+
+            DateFormat zulu = new XmlSchemaDateFormat();
+
+            log.debug("Current time: " + zulu.format(Calendar.getInstance().getTime()));
+            log.debug("Timestamp created: " + zulu.format(timestamp.getCreated().getTime()));
+            log.debug("Timestamp expires: " + zulu.format(timestamp.getExpires().getTime()));
+        }
+
+        // Validate whether the security semantics have expired
+        Calendar rightNow = Calendar.getInstance();
+        if (timestamp.getExpires().before(rightNow)) {
+            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "invalidTimestamp", new Object[]{"The security semantics of message have expired"});
+        }
+
+        return;
+    }
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/UsernameTokenProcessor.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/UsernameTokenProcessor.java?rev=280758&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/UsernameTokenProcessor.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/UsernameTokenProcessor.java Tue Sep 13 21:08:31 2005
@@ -0,0 +1,142 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.processor;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSDocInfo;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSecurityEngineResult;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.WSUsernameTokenPrincipal;
+import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.token.UsernameToken;
+import org.w3c.dom.Element;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Vector;
+
+public class UsernameTokenProcessor implements Processor {
+    private static Log log = LogFactory.getLog(UsernameTokenProcessor.class.getName());
+
+    public void handleToken(Element elem, Crypto crypto, Crypto decCrypto, CallbackHandler cb, WSDocInfo wsDocInfo, Vector returnResults) throws WSSecurityException {
+        if (log.isDebugEnabled()) {
+            log.debug("Found UsernameToken list element");
+        }
+        Principal lastPrincipalFound = handleUsernameToken((Element) elem, cb);
+        returnResults.add(0, new WSSecurityEngineResult(WSConstants.UT,
+                lastPrincipalFound, null, null, null));
+    }
+
+    /**
+     * Check the UsernameToken element. Depending on the password type
+     * contained in the element the processing differs. If the password type
+     * is password digest (a hashed password) then process the password
+     * commpletely here. Use the callback class to get a stored password
+     * perform hash algorithm and compare the result with the transmitted
+     * password.
+     * <p/>
+     * If the password is of type password text or any other yet unknown
+     * password type the delegate the password validation to the callback
+     * class. To do so the security engine hands over all necessary data to
+     * the callback class via the WSPasswordCallback object. To distinguish
+     * from digested usernam token the usage parameter of WSPasswordCallback
+     * is set to <code>USERNAME_TOKEN_UNKNOWN</code>
+     *
+     * @param token the DOM element that contains the UsernameToken
+     * @param cb    the refernce to the callback object
+     * @return WSUsernameTokenPrincipal that contain data that an application
+     *         may use to further validate the password/user combination.
+     * @throws WSSecurityException
+     */
+    public WSUsernameTokenPrincipal handleUsernameToken(Element token, CallbackHandler cb) throws WSSecurityException {
+        UsernameToken ut = new UsernameToken(token);
+        String user = ut.getName();
+        String password = ut.getPassword();
+        String nonce = ut.getNonce();
+        String createdTime = ut.getCreated();
+        String pwType = ut.getPasswordType();
+        if (log.isDebugEnabled()) {
+            log.debug("UsernameToken user " + user);
+            log.debug("UsernameToken password " + password);
+        }
+
+        Callback[] callbacks = new Callback[1];
+        if (ut.isHashed()) {
+            if (cb == null) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noCallback");
+            }
+
+            WSPasswordCallback pwCb = new WSPasswordCallback(user, WSPasswordCallback.USERNAME_TOKEN);
+            callbacks[0] = pwCb;
+            try {
+                cb.handle(callbacks);
+            } catch (IOException e) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noPassword",
+                        new Object[]{user});
+            } catch (UnsupportedCallbackException e) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noPassword",
+                        new Object[]{user});
+            }
+            String origPassword = pwCb.getPassword();
+            if (log.isDebugEnabled()) {
+                log.debug("UsernameToken callback password " + origPassword);
+            }
+            if (origPassword == null) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noPassword", new Object[]{user});
+            }
+            if (nonce != null && createdTime != null) {
+                String passDigest = UsernameToken.doPasswordDigest(nonce, createdTime, origPassword);
+                if (!passDigest.equals(password)) {
+                    throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
+                }
+            }
+        } else if (cb != null) {
+            WSPasswordCallback pwCb = new WSPasswordCallback(user, password,
+                    pwType, WSPasswordCallback.USERNAME_TOKEN_UNKNOWN);
+            callbacks[0] = pwCb;
+            try {
+                cb.handle(callbacks);
+            } catch (IOException e) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noPassword", new Object[]{user});
+            } catch (UnsupportedCallbackException e) {
+                throw new WSSecurityException(WSSecurityException.FAILURE,
+                        "noPassword", new Object[]{user});
+            }
+        }
+
+        WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal(user, ut.isHashed());
+        principal.setNonce(nonce);
+        principal.setPassword(password);
+        principal.setCreatedTime(createdTime);
+        principal.setPasswordType(pwType);
+
+        return principal;
+    }
+
+}

Added: webservices/wss4j/trunk/src/org/apache/ws/security/processor/X509Util.java
URL: http://svn.apache.org/viewcvs/webservices/wss4j/trunk/src/org/apache/ws/security/processor/X509Util.java?rev=280758&view=auto
==============================================================================
--- webservices/wss4j/trunk/src/org/apache/ws/security/processor/X509Util.java (added)
+++ webservices/wss4j/trunk/src/org/apache/ws/security/processor/X509Util.java Tue Sep 13 21:08:31 2005
@@ -0,0 +1,125 @@
+/*
+ * Copyright  2003-2004 The Apache Software Foundation.
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ */
+
+package org.apache.ws.security.processor;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSPasswordCallback;
+import org.apache.ws.security.WSSecurityException;
+import org.apache.ws.security.util.WSSecurityUtil;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import javax.crypto.SecretKey;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import java.io.IOException;
+
+public class X509Util {
+    private static Log log = LogFactory.getLog(X509Util.class.getName());
+
+    public static boolean isContent(Node encBodyData) {
+        /*
+         * Depending on the encrypted data type (Content or Element) the encBodyData either
+         * holds the element whose contents where encrypted, e.g. soapenv:Body, or the
+         * xenc:EncryptedData element (in case of Element encryption). In either case we need
+         * to get the xenc:EncryptedData element. So get it. The findElement method returns
+         * immediatly if its already the correct element.
+         * Then we can get the Type attribute.
+         */
+
+        Element tmpE = (Element) WSSecurityUtil.findElement(encBodyData,
+                "EncryptedData", WSConstants.ENC_NS);
+        String typeStr = null;
+        boolean content = true;
+        if (tmpE != null) {
+            typeStr = tmpE.getAttribute("Type");
+        }
+        if (typeStr != null) {
+            content = typeStr.equals(WSConstants.ENC_NS + "Content") ? true : false;
+        }
+        return content;
+    }
+
+    public static String getEncAlgo(Node encBodyData) throws WSSecurityException {
+        Element tmpE = (Element) WSSecurityUtil.findElement(encBodyData,
+                "EncryptionMethod", WSConstants.ENC_NS);
+
+        String symEncAlgo = null;
+        if (tmpE != null) {
+            symEncAlgo = tmpE.getAttribute("Algorithm");
+        }
+        if (symEncAlgo == null) {
+            throw new WSSecurityException
+                    (WSSecurityException.UNSUPPORTED_ALGORITHM,
+                            "noEncAlgo");
+        }
+        if (log.isDebugEnabled()) {
+            log.debug("Sym Enc Algo: " + symEncAlgo);
+        }
+        return symEncAlgo;
+    }
+
+    protected static SecretKey getSharedKey(Element keyInfoElem,
+                                            String algorithm,
+                                            CallbackHandler cb)
+            throws WSSecurityException {
+        String keyName = null;
+        Element keyNmElem =
+                (Element) WSSecurityUtil.getDirectChild(keyInfoElem,
+                        "KeyName",
+                        WSConstants.SIG_NS);
+        if (keyNmElem != null) {
+            keyNmElem.normalize();
+            Node tmpN;
+            if ((tmpN = keyNmElem.getFirstChild()) != null
+                    && tmpN.getNodeType() == Node.TEXT_NODE) {
+                keyName = tmpN.getNodeValue();
+            }
+        }
+        if (keyName == null) {
+            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY,
+                    "noKeyname");
+        }
+        WSPasswordCallback pwCb = new WSPasswordCallback(
+                keyName, WSPasswordCallback.KEY_NAME);
+        Callback[] callbacks = new Callback[1];
+        callbacks[0] = pwCb;
+        try {
+            cb.handle(callbacks);
+        } catch (IOException e) {
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "noPassword",
+                    new Object[]{keyName});
+        } catch (UnsupportedCallbackException e) {
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "noPassword",
+                    new Object[]{keyName});
+        }
+        byte[] decryptedData = pwCb.getKey();
+        if (decryptedData == null) {
+            throw new WSSecurityException(WSSecurityException.FAILURE,
+                    "noPassword",
+                    new Object[]{keyName});
+        }
+        return WSSecurityUtil.prepareSecretKey(algorithm, decryptedData);
+    }
+
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: wss4j-dev-unsubscribe@ws.apache.org
For additional commands, e-mail: wss4j-dev-help@ws.apache.org