KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > utils > SessionUtils


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Axis" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.jboss.axis.utils;
56
57 import org.jboss.logging.Logger;
58
59 import java.security.MessageDigest JavaDoc;
60 import java.security.NoSuchAlgorithmException JavaDoc;
61 import java.util.Random JavaDoc;
62
63 /**
64  * Code borrowed from AuthenticatorBase.java for generating a secure id's.
65  */

66 public class SessionUtils
67 {
68
69    /**
70     * Field log
71     */

72    private static Logger log = Logger.getLogger(SessionUtils.class.getName());
73
74    /**
75     * The default message digest algorithm to use if we cannot use
76     * the requested one.
77     */

78    protected static final String JavaDoc DEFAULT_ALGORITHM = "MD5";
79
80    /**
81     * The number of random bytes to include when generating a
82     * session identifier.
83     */

84    protected static final int SESSION_ID_BYTES = 16;
85
86    /**
87     * The message digest algorithm to be used when generating session
88     * identifiers. This must be an algorithm supported by the
89     * <code>java.security.MessageDigest</code> class on your platform.
90     */

91    protected static String JavaDoc algorithm = DEFAULT_ALGORITHM;
92
93    /**
94     * Return the MessageDigest implementation to be used when
95     * creating session identifiers.
96     */

97    protected static MessageDigest JavaDoc digest = null;
98
99    /**
100     * A random number generator to use when generating session identifiers.
101     */

102    protected static Random JavaDoc random = null;
103
104    /**
105     * The Java class name of the random number generator class to be used
106     * when generating session identifiers.
107     */

108    protected static String JavaDoc randomClass = "java.security.SecureRandom";
109
110    /**
111     * Host name/ip.
112     */

113    private static String JavaDoc thisHost = null;
114
115    /**
116     * Generate and return a new session identifier.
117     *
118     * @return a new session id
119     */

120    public static synchronized String JavaDoc generateSessionId()
121    {
122       // Generate a byte array containing a session identifier
123
byte bytes[] = new byte[SESSION_ID_BYTES];
124
125       getRandom().nextBytes(bytes);
126       bytes = getDigest().digest(bytes);
127
128       // Render the result as a String of hexadecimal digits
129
StringBuffer JavaDoc result = new StringBuffer JavaDoc();
130
131       for (int i = 0; i < bytes.length; i++)
132       {
133          byte b1 = (byte)((bytes[i] & 0xf0) >> 4);
134          byte b2 = (byte)(bytes[i] & 0x0f);
135
136          if (b1 < 10)
137          {
138             result.append((char)('0' + b1));
139          }
140          else
141          {
142             result.append((char)('A' + (b1 - 10)));
143          }
144          if (b2 < 10)
145          {
146             result.append((char)('0' + b2));
147          }
148          else
149          {
150             result.append((char)('A' + (b2 - 10)));
151          }
152       }
153       return (result.toString());
154    }
155
156    /**
157     * Generate and return a new session identifier.
158     *
159     * @return a new session.
160     */

161    public static synchronized Long JavaDoc generateSession()
162    {
163       return new Long JavaDoc(getRandom().nextLong());
164    }
165
166    /**
167     * Return the MessageDigest object to be used for calculating
168     * session identifiers. If none has been created yet, initialize
169     * one the first time this method is called.
170     *
171     * @return Message Digest
172     */

173    private static synchronized MessageDigest JavaDoc getDigest()
174    {
175       if (digest == null)
176       {
177          try
178          {
179             digest = MessageDigest.getInstance(algorithm);
180          }
181          catch (NoSuchAlgorithmException JavaDoc e)
182          {
183             try
184             {
185                digest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
186             }
187             catch (NoSuchAlgorithmException JavaDoc f)
188             {
189                digest = null;
190             }
191          }
192       }
193       return (digest);
194    }
195
196    /**
197     * Return the random number generator instance we should use for
198     * generating session identifiers. If there is no such generator
199     * currently defined, construct and seed a new one.
200     *
201     * @return Random object
202     */

203    private static synchronized Random JavaDoc getRandom()
204    {
205       if (random == null)
206       {
207          try
208          {
209             Class JavaDoc clazz = Class.forName(randomClass);
210
211             random = (Random JavaDoc)clazz.newInstance();
212             long seed = System.currentTimeMillis();
213             char entropy[] = getEntropy().toCharArray();
214
215             for (int i = 0; i < entropy.length; i++)
216             {
217                long update = ((byte)entropy[i]) << ((i % 8) * 8);
218
219                seed ^= update;
220             }
221             random.setSeed(seed);
222          }
223          catch (Exception JavaDoc e)
224          {
225             random = new java.util.Random JavaDoc();
226          }
227       }
228       return (random);
229    }
230
231    /**
232     * Method getEntropy
233     *
234     * @return a unique string
235     */

236    private static String JavaDoc getEntropy()
237    {
238       if (null == thisHost)
239       {
240          try
241          {
242             thisHost = java.net.InetAddress.getLocalHost().getHostName();
243          }
244          catch (java.net.UnknownHostException JavaDoc e)
245          {
246             log.error(Messages.getMessage("javaNetUnknownHostException00"),
247                     e);
248             thisHost = "localhost";
249          }
250       }
251       StringBuffer JavaDoc s = new StringBuffer JavaDoc();
252
253       // Unique string
254
s.append(s.hashCode()).append('.').append(System.currentTimeMillis())
255               .append(".AXIS@").append(thisHost);
256       return s.toString();
257    }
258 }
259
Popular Tags