KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > common > util > RandomGUID


1 package com.blandware.atleap.common.util;
2
3 /*
4  * RandomGUID from http://www.javaexchange.com/aboutRandomGUID.html
5  * @version 1.2.1 11/05/02
6  * @author Marc A. Mnich
7  *
8  * From www.JavaExchange.com, Open Software licensing
9  *
10  * 11/05/02 -- Performance enhancement from Mike Dubman.
11  * Moved InetAddr.getLocal to static block. Mike has measured
12  * a 10 fold improvement in run time.
13  * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object
14  * caused duplicate GUIDs to be produced. Random object
15  * is now only created once per JVM.
16  * 01/19/02 -- Modified random seeding and added new constructor
17  * to allow secure random feature.
18  * 01/14/02 -- Added random function seeding with JVM run time
19  *
20  */

21
22 import java.net.InetAddress JavaDoc;
23 import java.net.UnknownHostException JavaDoc;
24 import java.security.MessageDigest JavaDoc;
25 import java.security.NoSuchAlgorithmException JavaDoc;
26 import java.security.SecureRandom JavaDoc;
27 import java.util.Random JavaDoc;
28
29 /*
30  * In the multitude of java GUID generators, I found none that
31  * guaranteed randomness. GUIDs are guaranteed to be globally unique
32  * by using ethernet MACs, IP addresses, time elements, and sequential
33  * numbers. GUIDs are not expected to be random and most often are
34  * easy/possible to guess given a sample from a given generator.
35  * SQL Server, for example generates GUID that are unique but
36  * sequencial within a given instance.
37  *
38  * GUIDs can be used as security devices to hide things such as
39  * files within a filesystem where listings are unavailable (e.g. files
40  * that are served up from a Web server with indexing turned off).
41  * This may be desireable in cases where standard authentication is not
42  * appropriate. In this scenario, the RandomGUIDs are used as directories.
43  * Another example is the use of GUIDs for primary keys in a database
44  * where you want to ensure that the keys are secret. Random GUIDs can
45  * then be used in a URL to prevent hackers (or users) from accessing
46  * records by guessing or simply by incrementing sequential numbers.
47  *
48  * There are many other possiblities of using GUIDs in the realm of
49  * security and encryption where the element of randomness is important.
50  * This class was written for these purposes but can also be used as a
51  * general purpose GUID generator as well.
52  *
53  * RandomGUID generates truly random GUIDs by using the system's
54  * IP address (name/IP), system time in milliseconds (as an integer),
55  * and a very large random number joined together in a single String
56  * that is passed through an MD5 hash. The IP address and system time
57  * make the MD5 seed globally unique and the random number guarantees
58  * that the generated GUIDs will have no discernable pattern and
59  * cannot be guessed given any number of previously generated GUIDs.
60  * It is generally not possible to access the seed information (IP, time,
61  * random number) from the resulting GUIDs as the MD5 hash algorithm
62  * provides one way encryption.
63  *
64  * ----> Security of RandomGUID: <-----
65  * RandomGUID can be called one of two ways -- with the basic java Random
66  * number generator or a cryptographically strong random generator
67  * (SecureRandom). The choice is offered because the secure random
68  * generator takes about 3.5 times longer to generate its random numbers
69  * and this performance hit may not be worth the added security
70  * especially considering the basic generator is seeded with a
71  * cryptographically strong random seed.
72  *
73  * Seeding the basic generator in this way effectively decouples
74  * the random numbers from the time component making it virtually impossible
75  * to predict the random number component even if one had absolute knowledge
76  * of the System time. Thanks to Ashutosh Narhari for the suggestion
77  * of using the static method to prime the basic random generator.
78  *
79  * Using the secure random option, this class compies with the statistical
80  * random number generator tests specified in FIPS 140-2, Security
81  * Requirements for Cryptographic Modules, secition 4.9.1.
82  *
83  * I converted all the pieces of the seed to a String before handing
84  * it over to the MD5 hash so that you could print it out to make
85  * sure it contains the data you expect to see and to give a nice
86  * warm fuzzy. If you need better performance, you may want to stick
87  * to byte[] arrays.
88  *
89  * I believe that it is important that the algorithm for
90  * generating random GUIDs be open for inspection and modification.
91  * This class is free for all uses.
92  *
93  *
94  * - Marc
95  */

96
97 public class RandomGUID extends Object JavaDoc {
98
99     public String JavaDoc valueBeforeMD5 = "";
100     public String JavaDoc valueAfterMD5 = "";
101     private static Random JavaDoc myRand;
102     private static SecureRandom JavaDoc mySecureRand;
103
104     private static String JavaDoc s_id;
105
106     /*
107      * Static block to take care of one time secureRandom seed.
108      * It takes a few seconds to initialize SecureRandom. You might
109      * want to consider removing this static block or replacing
110      * it with a "time since first loaded" seed to reduce this time.
111      * This block will run only once per JVM instance.
112      */

113     static {
114         mySecureRand = new SecureRandom JavaDoc();
115         long secureInitializer = mySecureRand.nextLong();
116         myRand = new Random JavaDoc(secureInitializer);
117         try {
118             s_id = InetAddress.getLocalHost().toString();
119         } catch ( UnknownHostException JavaDoc e ) {
120             e.printStackTrace();
121         }
122
123     }
124
125
126     /*
127      * Default constructor. With no specification of security option,
128      * this constructor defaults to lower security, high performance.
129      */

130     public RandomGUID() {
131         getRandomGUID(false);
132     }
133
134     /*
135      * Constructor with security option. Setting secure true
136      * enables each random number generated to be cryptographically
137      * strong. Secure false defaults to the standard Random function seeded
138      * with a single cryptographically strong random number.
139      */

140     public RandomGUID(boolean secure) {
141         getRandomGUID(secure);
142     }
143
144     /*
145      * Method to generate the random GUID
146      */

147     private void getRandomGUID(boolean secure) {
148         MessageDigest JavaDoc md5 = null;
149         StringBuffer JavaDoc sbValueBeforeMD5 = new StringBuffer JavaDoc();
150
151         try {
152             md5 = MessageDigest.getInstance("MD5");
153         } catch ( NoSuchAlgorithmException JavaDoc e ) {
154             System.out.println("Error: " + e);
155         }
156
157         try {
158             long time = System.currentTimeMillis();
159             long rand = 0;
160
161             if ( secure ) {
162                 rand = mySecureRand.nextLong();
163             } else {
164                 rand = myRand.nextLong();
165             }
166
167             // This StringBuffer can be a long as you need; the MD5
168
// hash will always return 128 bits. You can change
169
// the seed to include anything you want here.
170
// You could even stream a file through the MD5 making
171
// the odds of guessing it at least as great as that
172
// of guessing the contents of the file!
173
sbValueBeforeMD5.append(s_id);
174             sbValueBeforeMD5.append(":");
175             sbValueBeforeMD5.append(Long.toString(time));
176             sbValueBeforeMD5.append(":");
177             sbValueBeforeMD5.append(Long.toString(rand));
178
179             valueBeforeMD5 = sbValueBeforeMD5.toString();
180             md5.update(valueBeforeMD5.getBytes());
181
182             byte[] array = md5.digest();
183             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
184             for ( int j = 0; j < array.length; ++j ) {
185                 int b = array[j] & 0xFF;
186                 if ( b < 0x10 ) {
187                     sb.append('0');
188                 }
189                 sb.append(Integer.toHexString(b));
190             }
191
192             valueAfterMD5 = sb.toString();
193
194         } catch ( Exception JavaDoc e ) {
195             System.out.println("Error:" + e);
196         }
197     }
198
199
200     /*
201      * Convert to the standard format for GUID
202      * (Useful for SQL Server UniqueIdentifiers, etc.)
203      * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
204      */

205     public String JavaDoc toString() {
206         String JavaDoc raw = valueAfterMD5.toUpperCase();
207         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
208         sb.append(raw.substring(0, 8));
209         sb.append("-");
210         sb.append(raw.substring(8, 12));
211         sb.append("-");
212         sb.append(raw.substring(12, 16));
213         sb.append("-");
214         sb.append(raw.substring(16, 20));
215         sb.append("-");
216         sb.append(raw.substring(20));
217
218         return sb.toString();
219     }
220
221     /*
222      * Demonstraton and self test of class
223      */

224     public static void main(String JavaDoc args[]) {
225         for ( int i = 0; i < 100; i++ ) {
226             RandomGUID myGUID = new RandomGUID();
227             System.out.println("Seeding String=" + myGUID.valueBeforeMD5);
228             System.out.println("rawGUID=" + myGUID.valueAfterMD5);
229             System.out.println("RandomGUID=" + myGUID.toString());
230         }
231     }
232 }
233
Popular Tags