1 16 package org.springframework.webflow.util; 17 18 35 36 import java.net.InetAddress ; 37 import java.net.UnknownHostException ; 38 import java.security.MessageDigest ; 39 import java.security.NoSuchAlgorithmException ; 40 import java.security.SecureRandom ; 41 import java.util.Random ; 42 43 106 public class RandomGuid extends Object { 107 108 private static Random random; 109 110 private static SecureRandom secureRandom; 111 112 private static String id; 113 114 private String valueBeforeMD5 = ""; 115 116 private String valueAfterMD5 = ""; 117 118 124 static { 125 secureRandom = new SecureRandom (); 126 long secureInitializer = secureRandom.nextLong(); 127 random = new Random (secureInitializer); 128 try { 129 id = InetAddress.getLocalHost().toString(); 130 } 131 catch (UnknownHostException e) { 132 throw new RuntimeException (e); 133 } 134 } 135 136 140 public RandomGuid() { 141 getRandomGuid(false); 142 } 143 144 150 public RandomGuid(boolean secure) { 151 getRandomGuid(secure); 152 } 153 154 157 private void getRandomGuid(boolean secure) { 158 MessageDigest md5 = null; 159 StringBuffer sbValueBeforeMD5 = new StringBuffer (); 160 161 try { 162 md5 = MessageDigest.getInstance("MD5"); 163 } 164 catch (NoSuchAlgorithmException e) { 165 throw new RuntimeException (e); 166 } 167 168 long time = System.currentTimeMillis(); 169 long rand = 0; 170 171 if (secure) { 172 rand = secureRandom.nextLong(); 173 } 174 else { 175 rand = random.nextLong(); 176 } 177 178 sbValueBeforeMD5.append(id); 185 sbValueBeforeMD5.append(":"); 186 sbValueBeforeMD5.append(Long.toString(time)); 187 sbValueBeforeMD5.append(":"); 188 sbValueBeforeMD5.append(Long.toString(rand)); 189 190 valueBeforeMD5 = sbValueBeforeMD5.toString(); 191 md5.update(valueBeforeMD5.getBytes()); 192 193 byte[] array = md5.digest(); 194 StringBuffer sb = new StringBuffer (); 195 for (int j = 0; j < array.length; ++j) { 196 int b = array[j] & 0xFF; 197 if (b < 0x10) 198 sb.append('0'); 199 sb.append(Integer.toHexString(b)); 200 } 201 valueAfterMD5 = sb.toString(); 202 } 203 204 209 public String toString() { 210 String raw = valueAfterMD5.toUpperCase(); 211 StringBuffer sb = new StringBuffer (); 212 sb.append(raw.substring(0, 8)); 213 sb.append("-"); 214 sb.append(raw.substring(8, 12)); 215 sb.append("-"); 216 sb.append(raw.substring(12, 16)); 217 sb.append("-"); 218 sb.append(raw.substring(16, 20)); 219 sb.append("-"); 220 sb.append(raw.substring(20)); 221 return sb.toString(); 222 } 223 } | Popular Tags |