1 package com.blandware.atleap.common.util; 2 3 21 22 import java.net.InetAddress ; 23 import java.net.UnknownHostException ; 24 import java.security.MessageDigest ; 25 import java.security.NoSuchAlgorithmException ; 26 import java.security.SecureRandom ; 27 import java.util.Random ; 28 29 96 97 public class RandomGUID extends Object { 98 99 public String valueBeforeMD5 = ""; 100 public String valueAfterMD5 = ""; 101 private static Random myRand; 102 private static SecureRandom mySecureRand; 103 104 private static String s_id; 105 106 113 static { 114 mySecureRand = new SecureRandom (); 115 long secureInitializer = mySecureRand.nextLong(); 116 myRand = new Random (secureInitializer); 117 try { 118 s_id = InetAddress.getLocalHost().toString(); 119 } catch ( UnknownHostException e ) { 120 e.printStackTrace(); 121 } 122 123 } 124 125 126 130 public RandomGUID() { 131 getRandomGUID(false); 132 } 133 134 140 public RandomGUID(boolean secure) { 141 getRandomGUID(secure); 142 } 143 144 147 private void getRandomGUID(boolean secure) { 148 MessageDigest md5 = null; 149 StringBuffer sbValueBeforeMD5 = new StringBuffer (); 150 151 try { 152 md5 = MessageDigest.getInstance("MD5"); 153 } catch ( NoSuchAlgorithmException 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 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 sb = new StringBuffer (); 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 e ) { 195 System.out.println("Error:" + e); 196 } 197 } 198 199 200 205 public String toString() { 206 String raw = valueAfterMD5.toUpperCase(); 207 StringBuffer sb = new StringBuffer (); 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 224 public static void main(String 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 |