KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mortbay > j2ee > session > GUIDGenerator


1 // ========================================================================
2
// $Id: GUIDGenerator.java,v 1.4 2004/05/09 20:30:47 gregwilkins Exp $
3
// Copyright 2002-2004 Mort Bay Consulting Pty. Ltd.
4
// ------------------------------------------------------------------------
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
// ========================================================================
15

16 /*
17  * JBoss, the OpenSource J2EE webOS
18  *
19  * Distributable under LGPL license.
20  * See terms of license at gnu.org.
21  */

22
23 package org.mortbay.j2ee.session;
24
25 // shamelessly distilled from
26
// org.jboss.ha.httpsession.server.ClusteredHTTPSessionService
27
// written by : sacha.labourey@cogito-info.ch
28

29 import java.security.MessageDigest JavaDoc;
30 import java.security.NoSuchAlgorithmException JavaDoc;
31 import java.security.SecureRandom JavaDoc;
32 import java.util.Random JavaDoc;
33
34 import javax.servlet.http.HttpServletRequest JavaDoc;
35
36 import org.jfox.ioc.logger.Logger;
37
38 public class
39   GUIDGenerator
40   implements IdGenerator
41 {
42   protected static final Logger _log=Logger.getLogger(GUIDGenerator.class);
43
44   protected final static int SESSION_ID_BYTES = 16; // We want 16 Bytes for the session-id
45
protected final static String JavaDoc SESSION_ID_HASH_ALGORITHM = "MD5";
46   protected final static String JavaDoc SESSION_ID_RANDOM_ALGORITHM = "SHA1PRNG";
47   protected final static String JavaDoc SESSION_ID_RANDOM_ALGORITHM_ALT = "IBMSecureRandom";
48
49   protected MessageDigest JavaDoc _digest=null;
50   protected Random JavaDoc _random=null;
51
52   /**
53      Generate a session-id that is not guessable
54      @return generated session-id
55   */

56   public synchronized String JavaDoc nextId(HttpServletRequest JavaDoc request)
57     {
58       if (_digest==null) {
59     _digest=getDigest();
60       }
61
62       if (_random==null) {
63     _random=getRandom();
64       }
65
66       byte[] bytes=new byte[SESSION_ID_BYTES];
67
68       // get random bytes
69
_random.nextBytes(bytes);
70
71       // Hash the random bytes
72
bytes=_digest.digest(bytes);
73
74       // Render the result as a String of hexadecimal digits
75
return encode(bytes);
76     }
77
78   /**
79      Encode the bytes into a String with a slightly modified Base64-algorithm
80      This code was written by Kevin Kelley <kelley@ruralnet.net>
81      and adapted by Thomas Peuss <jboss@peuss.de>
82      @param data The bytes you want to encode
83      @return the encoded String
84   */

85   protected String JavaDoc encode(byte[] data)
86     {
87       char[] out = new char[((data.length + 2) / 3) * 4];
88       char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-*".toCharArray();
89
90       //
91
// 3 bytes encode to 4 chars. Output is always an even
92
// multiple of 4 characters.
93
//
94
for (int i=0, index=0; i<data.length; i+=3, index+=4) {
95     boolean quad = false;
96     boolean trip = false;
97
98     int val = (0xFF & (int) data[i]);
99     val <<= 8;
100     if ((i+1) < data.length) {
101       val |= (0xFF & (int) data[i+1]);
102       trip = true;
103     }
104     val <<= 8;
105     if ((i+2) < data.length) {
106       val |= (0xFF & (int) data[i+2]);
107       quad = true;
108     }
109     out[index+3] = alphabet[(quad? (val & 0x3F): 64)];
110     val >>= 6;
111     out[index+2] = alphabet[(trip? (val & 0x3F): 64)];
112     val >>= 6;
113     out[index+1] = alphabet[val & 0x3F];
114     val >>= 6;
115     out[index+0] = alphabet[val & 0x3F];
116       }
117       return new String JavaDoc(out);
118     }
119
120   /**
121      get a random-number generator
122      @return a random-number generator
123   */

124   protected synchronized Random JavaDoc getRandom()
125     {
126       long seed;
127       Random JavaDoc random=null;
128
129       // Mix up the seed a bit
130
seed=System.currentTimeMillis();
131       seed^=Runtime.getRuntime().freeMemory();
132
133       try {
134     random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM);
135       }
136       catch (NoSuchAlgorithmException JavaDoc e)
137       {
138     try
139     {
140       random=SecureRandom.getInstance(SESSION_ID_RANDOM_ALGORITHM_ALT);
141     }
142     catch (NoSuchAlgorithmException JavaDoc e_alt)
143     {
144       _log.error("Could not generate SecureRandom for session-id randomness",e);
145       _log.error("Could not generate SecureRandom for session-id randomness",e_alt);
146       return null;
147     }
148       }
149
150       // set the generated seed for this PRNG
151
random.setSeed(seed);
152
153       return random;
154     }
155
156   /**
157      get a MessageDigest hash-generator
158      @return a hash generator
159   */

160   protected synchronized MessageDigest JavaDoc getDigest()
161     {
162       MessageDigest JavaDoc digest=null;
163
164       try {
165     digest=MessageDigest.getInstance(SESSION_ID_HASH_ALGORITHM);
166       } catch (NoSuchAlgorithmException JavaDoc e) {
167     _log.error("Could not generate MessageDigest for session-id hashing",e);
168     return null;
169       }
170
171       return digest;
172     }
173
174   public synchronized Object JavaDoc
175     clone()
176     {
177       try
178       {
179     return super.clone();
180       }
181       catch (CloneNotSupportedException JavaDoc e)
182       {
183     _log.warn("could not clone IdGenerator",e);
184     return null;
185       }
186     }
187 }
188
Popular Tags