1   package com.atlassian.security.auth.trustedapps;
2   
3   import java.net.InetAddress;
4   import java.security.SecureRandom;
5   
6   /**
7    * Utility class for UID generation.
8    */
9   public class UIDGenerator
10  {
11      /**
12  	 * Generates a a 32 character long unique ID. The generation is based on four components:
13  	 * - IP address
14  	 * - current time in milliseconds
15  	 * - secure random number
16  	 * - identity hash code of a newly created object
17  	 */
18  	public static String generateUID()
19      {
20          try
21          {
22          	String strRetVal = "";
23          	String strTemp = "";
24              // Get IPAddress Segment
25              InetAddress addr = InetAddress.getLocalHost();
26  
27              byte[] ipaddr = addr.getAddress();
28              for (int i=0; i<ipaddr.length; i++)
29              {
30                  Byte b = new Byte(ipaddr[i]);
31  
32                  strTemp = Integer.toHexString (b.intValue() & 0x000000ff);
33                  while (strTemp.length() < 2)
34                  {
35                      strTemp = '0' + strTemp;
36                  }
37                  strRetVal += strTemp;
38              }
39  
40  
41              //Get CurrentTimeMillis() segment
42              strTemp = Long.toHexString(System.currentTimeMillis());
43              while (strTemp.length () < 12)
44              {
45                  strTemp = '0' + strTemp;
46              }
47              strRetVal += strTemp;
48  
49              //Get Random Segment
50              SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
51  
52              strTemp = Integer.toHexString(prng.nextInt());
53              while (strTemp.length () < 8)
54              {
55                  strTemp = '0' + strTemp;
56              }
57  
58              strRetVal += strTemp.substring(4);
59  
60              //Get IdentityHash() segment
61              strTemp = Long.toHexString(System.identityHashCode(new Object()));
62              while (strTemp.length() < 8)
63              {
64                  strTemp = '0' + strTemp;
65              }
66              strRetVal += strTemp;
67              return strRetVal.toUpperCase();
68          }
69          catch(java.net.UnknownHostException e)
70          {
71          	throw new RuntimeException(e);
72          }
73          catch(java.security.NoSuchAlgorithmException e)
74          {
75          	throw new RuntimeException(e);
76          }
77      }
78  }