View Javadoc

1   package spok;
2   
3   import java.security.MessageDigest;
4   import java.security.NoSuchAlgorithmException;
5   import java.security.SecureRandom;
6   
7   /**
8    * Class for generating unique Identifiers
9    * 
10   * @author hel
11   * @created 22. September 2004
12   */
13  public class GenerateId {
14  	private static String spectrumID;
15  
16  	/**
17  	 * Generates a unique identifier by generating a random number and getting
18  	 * its digest
19  	 * 
20  	 * @return the new SpectrumID
21  	 */
22  	public static String GenerateId() {
23  		try {
24  			// Initialize SecureRandom
25  			// This is a lengthy operation, to be done only upon
26  			// initialization of the application
27  			SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
28  
29  			// generate a random number
30  			String randomNum = new Integer(prng.nextInt()).toString();
31  
32  			// get its digest
33  			MessageDigest sha = MessageDigest.getInstance("SHA-1");
34  			byte[] result = sha.digest(randomNum.getBytes());
35  
36  			spectrumID = hexEncode(result);
37  			spectrumID = "sid_" + spectrumID;
38  		} catch (NoSuchAlgorithmException ex) {
39  			System.err.println(ex);
40  		}
41  		return spectrumID;
42  	}
43  
44  	/**
45  	 * The byte[] returned by MessageDigest does not have a nice textual
46  	 * representation, so some form of encoding is usually performed.
47  	 * 
48  	 * This implementation follows the example of David Flanagan's book "Java In
49  	 * A Nutshell", and converts a byte array into a String of hex characters.
50  	 * 
51  	 * Another popular alternative is to use a "Base64" encoding.
52  	 * 
53  	 * @param aInput
54  	 *            byte array build by GenerateId().
55  	 * @return the resulting unique identifier string.
56  	 */
57  	private static String hexEncode(byte[] aInput) {
58  		StringBuffer result = new StringBuffer();
59  		char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
60  				'a', 'b', 'c', 'd', 'e', 'f' };
61  		for (int idx = 0; idx < aInput.length; ++idx) {
62  			byte b = aInput[idx];
63  			result.append(digits[(b & 0xf0) >> 4]);
64  			result.append(digits[b & 0x0f]);
65  		}
66  		return result.toString();
67  	}
68  }