/*
 * Created on 2004/11/05
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.jware.util.crypt;

import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author jrmt
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class UniqIDUtils {

    /**
     * 
     */
    public UniqIDUtils() {
        super();
    }

    public static void main (String[] arguments) {

        System.out.println("UniqID = " + generateUniqID() );
    
    }

    
    public static String generateUniqID () {
        
        String uniqID = null;
        
        try {
          //Initialize SecureRandom
          //This is a lengthy operation, to be done only upon
          //initialization of the application
          SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

          //generate a random number
          String randomNum = new Integer( prng.nextInt() ).toString();

          //get its digest
          MessageDigest sha = MessageDigest.getInstance("SHA-1");
          byte[] result =  sha.digest( randomNum.getBytes() );

          uniqID = hexEncode(result);

        }
        catch ( NoSuchAlgorithmException ex ) {
          System.err.println(ex);
        }
        
        return uniqID;
      }

      /**
      * The byte[] returned by MessageDigest does not have a nice
      * textual representation, so some form of encoding is usually performed.
      *
      * This implementation follows the example of David Flanagan's book
      * "Java In A Nutshell", and converts a byte array into a String
      * of hex characters.
      *
      * Another popular alternative is to use a "Base64" encoding.
      */
      static private String hexEncode( byte[] aInput){
        StringBuffer result = new StringBuffer();
        char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','A','B','C','D','E','F'};
        for ( int idx = 0; idx < aInput.length; ++idx) {
          byte b = aInput[idx];
          result.append( digits[ (b&0xf0) >> 4 ] );
          result.append( digits[ b&0x0f] );
        }
        return result.toString();
      }
    
}
