1 package org.roller.util; 2 20 21 import java.net.InetAddress ; 22 import java.net.UnknownHostException ; 23 import java.security.MessageDigest ; 24 import java.security.NoSuchAlgorithmException ; 25 import java.security.SecureRandom ; 26 import java.util.Random ; 27 28 95 96 public class RandomGUID extends Object { 97 98 public String valueBeforeMD5 = ""; 99 public String valueAfterMD5 = ""; 100 private static Random myRand; 101 private static SecureRandom mySecureRand; 102 103 private static String s_id; 104 105 112 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) sb.append('0'); 187 sb.append(Integer.toHexString(b)); 188 } 189 190 valueAfterMD5 = sb.toString(); 191 192 } catch (Exception e) { 193 System.out.println("Error:" + e); 194 } 195 } 196 197 198 203 public String toString() { 204 String raw = valueAfterMD5.toUpperCase(); 205 StringBuffer sb = new StringBuffer (); 206 sb.append(raw.substring(0, 8)); 207 sb.append("-"); 208 sb.append(raw.substring(8, 12)); 209 sb.append("-"); 210 sb.append(raw.substring(12, 16)); 211 sb.append("-"); 212 sb.append(raw.substring(16, 20)); 213 sb.append("-"); 214 sb.append(raw.substring(20)); 215 216 return sb.toString(); 217 } 218 219 222 public static void main(String args[]) { 223 for (int i=0; i< 100; i++) { 224 RandomGUID myGUID = new RandomGUID(); 225 System.out.println("Seeding String=" + myGUID.valueBeforeMD5); 226 System.out.println("rawGUID=" + myGUID.valueAfterMD5); 227 System.out.println("RandomGUID=" + myGUID.toString()); 228 } 229 } 230 } 231 | Popular Tags |