You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-dev@axis.apache.org by di...@apache.org on 2003/10/14 14:05:02 UTC

cvs commit: ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token BinarySecurity.java PKIPathSecurity.java Reference.java SecurityTokenReference.java UsernameToken.java X509Security.java

dims        2003/10/14 05:05:02

  Added:       contrib/wss4j/src/org/apache/ws/security/message/token
                        BinarySecurity.java PKIPathSecurity.java
                        Reference.java SecurityTokenReference.java
                        UsernameToken.java X509Security.java
  Log:
  ******* WORK IN PROGRESS *******
  
  Initial check-in of my sandbox for ws-security related code.
  
  Revision  Changes    Path
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/BinarySecurity.java
  
  Index: BinarySecurity.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.axis.encoding.Base64;
  import org.apache.axis.utils.XMLUtils;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  
  import javax.xml.namespace.QName;
  
  /**
   * Binary Security Token.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class BinarySecurity {
      public static final QName TOKEN = new QName(WSConstants.WSSE_NS, "BinarySecurityToken");
      public static final QName BASE64_ENCODING = new QName(WSConstants.WSSE_NS, "Base64Binary");
      protected Element element = null;
  
      /**
       * Constructor.
       * <p>
       * @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)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType", new Object[]{el});
          }
          if (!getEncodingType().equals(BASE64_ENCODING)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badEncoding", new Object[]{getEncodingType()});
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public BinarySecurity(Document doc) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS, "wsse:BinarySecurityToken");
          WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
          setEncodingType(BASE64_ENCODING);
          this.element.appendChild(doc.createTextNode(""));
      }
  
      /**
       * get the value type.
       * <p>
       * @return   
       */
      public QName getValueType() {
          String value = this.element.getAttribute("ValueType");
          return XMLUtils.getQNameFromString(value, this.element);
      }
  
      /**
       * set the value type.
       * <p>
       * @param  type   
       */
      protected void setValueType(QName type) {
          this.element.setAttributeNS(null, "ValueType", XMLUtils.getStringForQName(type, this.element));
      }
  
      /**
       * get the encoding type.
       * <p>
       * @return   
       */
      public QName getEncodingType() {
          String value = this.element.getAttribute("EncodingType");
          return XMLUtils.getQNameFromString(value, this.element);
      }
  
      /**
       * set the encoding type.
       * <p>
       * @param  encoding   
       */
      protected void setEncodingType(QName encoding) {
          this.element.setAttributeNS(null, "EncodingType", XMLUtils.getStringForQName(encoding, this.element));
      }
  
      /**
       * get the byte array containing token information.
       * <p>
       * @return   
       */
      public byte[] getToken() {
          Text node = getFirstNode();
          if (node == null) {
              return null;
          }
          try {
              return Base64.decode(node.getData());
          } catch (Exception e) {
              return null;
          }
      }
  
      /**
       * set the token information.
       * <p>
       * @param  data   
       */
      protected void setToken(byte[] data) {
          if (data == null) {
              throw new IllegalArgumentException("data == null");
          }
          Text node = getFirstNode();
          node.setData(Base64.encode(data));
      }
  
      /**
       * return the first text node.
       * <p>
       * @return   
       */
      protected Text getFirstNode() {
          Node node = this.element.getFirstChild();
          return ((node != null) && node instanceof Text) ? (Text) node : null;
      }
  
      /**
       * return the dom element.
       * <p>
       * @return   
       */
      public Element getElement() {
          return this.element;
      }
  
      /**
       * get the id.
       * <p>
       * @return   
       */
      public String getID() {
          return this.element.getAttributeNS(WSConstants.WSU_NS, "Id");
      }
  
      /**
       * set the id.
       * <p>
       * @param  id   
       */
      public void setID(String id) {
          String prefix = WSSecurityUtil.setNamespace(this.element, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
          this.element.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
      }
  
      /**
       * return the string representation of the token.
       * <p>
       * @return   
       */
      public String toString() {
          return XMLUtils.ElementToString(this.element);
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/PKIPathSecurity.java
  
  Index: PKIPathSecurity.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.components.crypto.CryptoFactory;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import javax.xml.namespace.QName;
  import java.io.IOException;
  import java.security.GeneralSecurityException;
  import java.security.cert.CertificateEncodingException;
  import java.security.cert.X509Certificate;
  
  /**
   * PKIPath Security Token.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class PKIPathSecurity extends BinarySecurity {
      public static final QName TYPE = new QName(WSConstants.WSSE_NS, "PKIPath");
  
      /**
       * Constructor.
       * <p>
       * @param   elem                  
       * @throws  WSSecurityException  
       */
      public PKIPathSecurity(Element elem) throws WSSecurityException {
          super(elem);
          if (!getValueType().equals(TYPE)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "invalidValueType", new Object[]{TYPE, getValueType()});
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public PKIPathSecurity(Document doc) {
          super(doc);
          setValueType(TYPE);
      }
  
      /**
       * get the X509Certificate array.
       * <p>
       * @param   reverse                    
       * @return                             
       * @throws  GeneralSecurityException  
       * @throws  IOException               
       */
      public X509Certificate[] getX509Certificates(boolean reverse) throws GeneralSecurityException, IOException {
          byte[] data = getToken();
          if (data == null) {
              return null;
          }
          X509Certificate[] certs = null;
          certs = CryptoFactory.getInstance().getX509Certificates(data, reverse);
          return certs;
      }
  
      /**
       * set the X509Certificate array.
       * <p>
       * @param   certs                          
       * @param   reverse                        
       * @throws  CertificateEncodingException  
       * @throws  IOException                   
       */
      public void setX509Certificates(X509Certificate[] certs, boolean reverse) throws CertificateEncodingException, IOException {
          if (certs == null) {
              throw new IllegalArgumentException("data == null");
          }
          byte[] data = CryptoFactory.getInstance().getCertificateData(reverse, certs);
          setToken(data);
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/Reference.java
  
  Index: Reference.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.axis.utils.XMLUtils;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import javax.xml.namespace.QName;
  
  /**
   * Reference.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class Reference {
      public static final QName TOKEN = new QName(WSConstants.WSSE_NS, "Reference");
      protected Element element = null;
  
      /**
       * Constructor.
       * <p>
       * @param   elem                  
       * @throws  WSSecurityException  
       */
      public Reference(Element elem) throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(), this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.FAILURE, "badElement", new Object[]{TOKEN, el});
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public Reference(Document doc) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Reference");
      }
  
      /**
       * get the dom element.
       * <p>
       * @return   
       */
      public Element getElement() {
          return this.element;
      }
  
      /**
       * get the URI.
       * <p>
       * @return   
       */
      public String getURI() {
          return this.element.getAttribute("URI");
      }
  
      /**
       * set the URI.
       * <p>
       * @param  uri   
       */
      public void setURI(String uri) {
          this.element.setAttribute("URI", uri);
      }
  
      /**
       * return the string representation.
       * <p>
       * @return   
       */
      public String toString() {
          return XMLUtils.ElementToString(this.element);
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/SecurityTokenReference.java
  
  Index: SecurityTokenReference.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.axis.utils.XMLUtils;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  
  import javax.xml.namespace.QName;
  
  /**
   * Security Token Reference.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class SecurityTokenReference {
      public static final QName TOKEN = new QName(WSConstants.WSSE_NS, "SecurityTokenReference");
      protected Element element = null;
  
      /**
       * Constructor.
       * <p>
       * @param   elem                  
       * @throws  WSSecurityException  
       */
      public SecurityTokenReference(Element elem) throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(), this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.FAILURE, "badElement", new Object[]{TOKEN, el});
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public SecurityTokenReference(Document doc) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS, "wsse:SecurityTokenReference");
      }
  
      /**
       * set the reference.
       * <p>
       * @param  ref   
       */
      public void setReference(Reference ref) {
          Element elem = getFirstElement();
          if (elem != null) {
              this.element.replaceChild(ref.getElement(), elem);
          } else {
              this.element.appendChild(ref.getElement());
          }
      }
  
      /**
       * get the reference.
       * <p>
       * @return                        
       * @throws  WSSecurityException  
       */
      public Reference getReference() throws WSSecurityException {
          Element elem = getFirstElement();
          return (elem == null) ? null : new Reference(elem);
      }
  
      /**
       * get the first child element.
       * <p>
       * @return   
       */
      private Element getFirstElement() {
          for (Node currentChild = this.element.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
              if (currentChild instanceof Element) {
                  return (Element) currentChild;
              }
          }
          return null;
      }
  
      /**
       * get the dom element.
       * <p>
       * @return   
       */
      public Element getElement() {
          return this.element;
      }
  
      /**
       * get the id.
       * <p>
       * @return   
       */
      public String getID() {
          return this.element.getAttributeNS(WSConstants.WSU_NS, "Id");
      }
  
      /**
       * set the id.
       * <p>
       * @param  id   
       */
      public void setID(String id) {
          this.element.setAttributeNS(WSConstants.WSU_NS, "wsu:Id", id);
      }
  
      /**
       * return the string representation.
       * <p>
       * @return   
       */
      public String toString() {
          return XMLUtils.ElementToString(this.element);
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/UsernameToken.java
  
  Index: UsernameToken.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.axis.encoding.Base64;
  import org.apache.axis.utils.XMLUtils;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.Text;
  
  import javax.crypto.Mac;
  import javax.crypto.spec.SecretKeySpec;
  import javax.xml.namespace.QName;
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;
  import java.security.SecureRandom;
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.TimeZone;
  
  /**
   * Binary Security Token.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class UsernameToken {
      public static final QName TOKEN = new QName(WSConstants.WSSE_NS, "UsernameToken");
      protected Element element = null;
      protected Element elementUsername = null;
      protected Element elementPassword = null;
      protected Element elementNonce = null;
      protected Element elementCreated = null;
      protected boolean hashed = true;
      private static SecureRandom random = null;
      String password = null;
  
      static {
          try {
              random = SecureRandom.getInstance("SHA1PRNG");
          } catch (NoSuchAlgorithmException nsae) {
              nsae.printStackTrace();
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param   elem                  
       * @throws  WSSecurityException  
       */
      public UsernameToken(Element elem) throws WSSecurityException {
          this.element = elem;
          QName el = new QName(this.element.getNamespaceURI(), this.element.getLocalName());
          if (!el.equals(TOKEN)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType", new Object[]{el});
          }
          elementUsername = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.WSSE_NS, "Username");
          elementPassword = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.WSSE_NS, "Password");
          elementNonce = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.WSSE_NS, "Nonce");
          elementCreated = (Element) WSSecurityUtil.getDirectChild(element, WSConstants.WSU_NS, "Created");
          if (elementUsername == null || elementPassword == null || elementNonce == null || elementCreated == null) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "badTokenType", new Object[]{el});
          }
          String type = elementPassword.getAttributeNS(WSConstants.WSSE_NS, "Type");
          if (type.equals("PasswordDigest")) {
              hashed = true;
          } else {
              hashed = false;
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public UsernameToken(Document doc) {
          this.element = doc.createElementNS(WSConstants.WSSE_NS, "wsse:UsernameToken");
          WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
          this.elementUsername = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Username");
          WSSecurityUtil.setNamespace(this.elementUsername, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
          this.elementUsername.appendChild(doc.createTextNode(""));
          element.appendChild(elementUsername);
          this.elementPassword = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Password");
          WSSecurityUtil.setNamespace(this.elementPassword, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
          this.elementPassword.appendChild(doc.createTextNode(""));
          element.appendChild(elementPassword);
          this.elementPassword.setAttribute("Type", "wsse:PasswordDigest");
          byte[] nonceValue = new byte[16];
          random.nextBytes(nonceValue);
          this.elementNonce = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Nonce");
          WSSecurityUtil.setNamespace(this.elementNonce, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);
          this.elementNonce.appendChild(doc.createTextNode(Base64.encode(nonceValue)));
          element.appendChild(elementNonce);
          SimpleDateFormat zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
          zulu.setTimeZone(TimeZone.getTimeZone("GMT"));
          Calendar rightNow = Calendar.getInstance();
          this.elementCreated = doc.createElementNS(WSConstants.WSU_NS, "wsu:Created");
          WSSecurityUtil.setNamespace(this.elementCreated, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
          this.elementCreated.appendChild(doc.createTextNode(zulu.format(rightNow.getTime())));
          element.appendChild(elementCreated);
      }
  
      /**
       * Get the user name.
       * <p>
       * @return   
       */
      public String getName() {
          return getFirstNode(this.elementUsername).getData();
      }
  
      /**
       * Set the user name.
       * <p>
       * @param  name   
       */
      public void setName(String name) {
          Text node = getFirstNode(this.elementUsername);
          node.setData(name);
      }
  
      /**
       * Get the nonce.
       * <p>
       * @return   
       */
      public String getNonce() {
          return getFirstNode(this.elementNonce).getData();
      }
  
      /**
       * Set the nonce.
       * <p>
       * @param  nonce   
       */
      public void setNonce(String nonce) {
          Text node = getFirstNode(this.elementNonce);
          node.setData(nonce);
      }
  
      /**
       * Get the created timestamp.
       * <p>
       * @return   
       */
      public String getCreated() {
          return getFirstNode(this.elementCreated).getData();
      }
  
      /**
       * Set the created timestamp.
       * <p>
       * @param  created   
       */
      public void setCreated(String created) {
          Text node = getFirstNode(this.elementCreated);
          node.setData(created);
      }
  
      /**
       * Get the password string.
       * <p>
       * @return   
       */
      public String getPassword() {
          Text node = getFirstNode(this.elementPassword);
          if (node == null) {
              return null;
          }
          return node.getData();
      }
  
      /**
       * Set the password string.
       * <p>
       * @param  pwd   
       */
      public void setPassword(String pwd) {
          this.password = pwd;
          if (pwd == null) {
              throw new IllegalArgumentException("pwd == null");
          }
          Text node = getFirstNode(this.elementPassword);
          try {
              if (!hashed) {
                  node.setData(pwd);
                  this.elementPassword.setAttribute("Type", "wsse:PasswordText");
              } else {
                  byte[] b1 = Base64.decode(getNonce());
                  byte[] b2 = getCreated().getBytes("UTF-8");
                  byte[] b3 = pwd.getBytes("UTF-8");
                  byte[] b4 = new byte[b1.length + b2.length + b3.length];
                  int i = 0;
                  int count = 0;
                  for (i = 0; i < b1.length; i++) {
                      b4[count++] = b1[i];
                  }
                  for (i = 0; i < b2.length; i++) {
                      b4[count++] = b2[i];
                  }
                  for (i = 0; i < b3.length; i++) {
                      b4[count++] = b3[i];
                  }
                  MessageDigest sha = MessageDigest.getInstance("SHA-1");
                  sha.reset();
                  sha.update(b4);
                  node.setData(Base64.encode(sha.digest()));
                  this.elementPassword.setAttribute("Type", "wsse:PasswordDigest");
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  
      /**
       * return the first text node.
       * <p>
       * @param   e   
       * @return      
       */
      private Text getFirstNode(Element e) {
          Node node = e.getFirstChild();
          return ((node != null) && node instanceof Text) ? (Text) node : null;
      }
  
      /**
       * return the dom element.
       * <p>
       * @return   
       */
      public Element getElement() {
          return this.element;
      }
  
      /**
       * return the string representation of the token.
       * <p>
       * @return   
       */
      public String toString() {
          return XMLUtils.ElementToString(this.element);
      }
  
      /**
       * get the id.
       * <p>
       * @return   
       */
      public String getID() {
          return this.element.getAttributeNS(WSConstants.WSU_NS, "Id");
      }
  
      /**
       * set the id.
       * <p>
       * @param  id   
       */
      public void setID(String id) {
          String prefix = WSSecurityUtil.setNamespace(this.element, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
          this.element.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
      }
  
      /**
       * Get the secret key as per WS-Trust spec.
       * <p>
       * @return   
       */
      public byte[] getSecretKey() {
          byte[] key = null;
          try {
              Mac mac = Mac.getInstance("HMACSHA1");
              byte[] password = this.password.getBytes("UTF-8");
              byte[] label = "WS-Security".getBytes("UTF-8");
              byte[] nonce = Base64.decode(getNonce());
              byte[] created = getCreated().getBytes("UTF-8");
              byte[] seed = new byte[label.length + nonce.length + created.length];
              int i = 0;
              int count = 0;
              for (i = 0; i < label.length; i++) {
                  seed[count++] = label[i];
              }
              for (i = 0; i < nonce.length; i++) {
                  seed[count++] = nonce[i];
              }
              for (i = 0; i < created.length; i++) {
                  seed[count++] = created[i];
              }
              key = P_hash(password, seed, mac, 128);
              System.out.println("password   :" + Base64.encode(password));
              System.out.println("label      :" + Base64.encode(label));
              System.out.println("nonce      :" + Base64.encode(nonce));
              System.out.println("created    :" + Base64.encode(created));
              System.out.println("seed       :" + Base64.encode(seed));
              System.out.println("Key        :" + Base64.encode(key));
          } catch (Exception e) {
              e.printStackTrace();
          }
          return key;
      }
  
      /**
       * P_hash defined in RFC for TLS.
       * <p>
       * @param   secret      
       * @param   seed        
       * @param   mac         
       * @param   required    
       * @return              
       * @throws  Exception  
       */
      private static byte[] P_hash(byte[] secret, byte[] seed, Mac mac, int required) throws Exception {
          byte[] out = new byte[required];
          int offset = 0, tocpy;
          byte[] A, tmp;
          A = seed;
          while (required > 0) {
              SecretKeySpec key = new SecretKeySpec(secret, "HMACSHA1");
              mac.init(key);
              mac.update(A);
              A = mac.doFinal();
              mac.reset();
              mac.init(key);
              mac.update(A);
              mac.update(seed);
              tmp = mac.doFinal();
              tocpy = min(required, tmp.length);
              System.arraycopy(tmp, 0, out, offset, tocpy);
              offset += tocpy;
              required -= tocpy;
          }
          return out;
      }
      
      /*
      public static void main(String[] args) throws Exception {
          byte[] secret = Base64.decode("A4BKgeqUKi9VDwWyYPDrskwCwEQ5RIqH");
          byte[] seed = Base64.decode("bWFzdGVyIHNlY3JldAAAAAAAAAAAAAAAAAAAAAAy+BE8DDEUf+XnAynZEVU0PUQR4QHesAbNCmt8/Ry6NqBELuBAiZV4Z0FuCT58Fi8=");
          int required = 48;
          Mac mac = Mac.getInstance("HMACSHA1");
          byte[] out = UsernameToken.P_hash(secret, seed, mac, 48);
          System.out.println(Base64.encode(out));
          //UCbz0pT2DxRfx4IpY6iWRE0KCa4Fg9JKNRlrxE8AtjNjb1NEK17NI6XdrMRMOKM2
      }
      */
  
      /**
       * helper method.
       * <p>
       * @param   a   
       * @param   b   
       * @return      
       */
      private static int min(int a, int b) {
          return (a > b) ? b : a;
      }
  }
  
  
  1.1                  ws-axis/contrib/wss4j/src/org/apache/ws/security/message/token/X509Security.java
  
  Index: X509Security.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Axis" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  package org.apache.ws.security.message.token;
  
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.components.crypto.CryptoFactory;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import javax.xml.namespace.QName;
  import java.io.ByteArrayInputStream;
  import java.security.GeneralSecurityException;
  import java.security.cert.CertificateEncodingException;
  import java.security.cert.X509Certificate;
  
  /**
   * X509 Security Token.
   * <p>
   * @author  Davanum Srinivas (dims@yahoo.com).
   */
  public class X509Security extends BinarySecurity {
      public static final QName TYPE = new QName(WSConstants.WSSE_NS, "X509v3");
  
      /**
       * Constructor.
       * <p>
       * @param   elem                  
       * @throws  WSSecurityException  
       */
      public X509Security(Element elem) throws WSSecurityException {
          super(elem);
          if (!getValueType().equals(TYPE)) {
              throw new WSSecurityException(WSSecurityException.INVALID_SECURITY_TOKEN, "invalidValueType", new Object[]{TYPE, getValueType()});
          }
      }
  
      /**
       * Constructor.
       * <p>
       * @param  doc   
       */
      public X509Security(Document doc) {
          super(doc);
          setValueType(TYPE);
      }
  
      /**
       * get the X509Certificate certificate.
       * <p>
       * @return                             
       * @throws  GeneralSecurityException  
       */
      public X509Certificate getX509Certificate() throws GeneralSecurityException {
          byte[] data = getToken();
          if (data == null) {
              return null;
          }
          ByteArrayInputStream in = new ByteArrayInputStream(data);
          return CryptoFactory.getInstance().loadCertificate(in);
      }
  
      /**
       * set the X509Certificate.
       * <p>
       * @param   cert                           
       * @throws  CertificateEncodingException  
       */
      public void setX509Certificate(X509Certificate cert) throws CertificateEncodingException {
          if (cert == null) {
              throw new IllegalArgumentException("data == null");
          }
          setToken(cert.getEncoded());
      }
  }