1 25 26 package com.rift.coad.lib.common; 28 29 import com.rift.coad.lib.common.*; 31 import java.net.InetAddress ; 32 import java.net.UnknownHostException ; 33 import java.security.SecureRandom ; 34 import java.security.MessageDigest ; 35 36 37 44 public class RandomGuid { 45 46 private static SecureRandom mySecureRand; 48 49 private String s_id = null; 51 public String guid = ""; 52 53 54 61 62 static { 63 mySecureRand = new SecureRandom (); 64 } 65 66 67 73 private RandomGuid() throws Exception { 74 try { 75 s_id = InetAddress.getLocalHost().toString(); 76 } catch (UnknownHostException ex) { 77 throw new Exception ("Failed to retrieve the host information [" 78 + ex.getMessage(),ex); 79 } 80 81 generateRandomGUID(); 83 } 84 85 86 92 public static RandomGuid getInstance() throws Exception { 93 return new RandomGuid(); 94 } 95 96 97 102 private void generateRandomGUID() throws Exception { 103 try { 104 StringBuffer sbValueBeforeMD5 = new StringBuffer (); 105 MessageDigest md5 = null; 107 md5 = MessageDigest.getInstance("MD5"); 108 109 110 long time = new java.util.Date ().getTime(); 111 String rand = ""; 112 113 synchronized (mySecureRand) { 115 for (int count = 0; count < 20; count++) 116 { 117 rand += Long.toString(mySecureRand.nextLong()); 118 } 119 } 120 121 sbValueBeforeMD5.append(s_id); 128 sbValueBeforeMD5.append(":"); 129 sbValueBeforeMD5.append(Long.toString(time)); 130 sbValueBeforeMD5.append(":"); 131 sbValueBeforeMD5.append(rand); 132 133 String valueBeforeMD5 = sbValueBeforeMD5.toString(); 135 md5.update(valueBeforeMD5.getBytes()); 136 byte[] array = md5.digest(); 137 StringBuffer sb = new StringBuffer (); 138 for (int j = 0; j < array.length; ++j) { 139 int b = array[j] & 0xFF; 140 if (b < 0x10) sb.append('0'); 141 sb.append(Integer.toHexString(b)); 142 } 143 144 guid = sb.toString(); 145 } catch (Exception ex) { 146 throw new Exception ("Failed to generate the GUID : " + 147 ex.getMessage(),ex); 148 } 149 } 150 151 152 157 public String getGuid() { 158 return guid; 159 } 160 161 162 167 public String toString() { 168 return guid; 169 } 170 } 171 | Popular Tags |