Thursday 8 August 2013

What is UUID(Universally Unique Identifiers)?



Generating Unique Id's

 UUID: - Universally Unique Identifiers

Question: - What is UUID?

Answer:-  A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. The UUID is generated using a cryptographically strong pseudo random number generator. A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens) or 2 128 .

For example: 550e8400-e29b-41d4-a716-446655440000

Java UUID Generator also provides a good quality UUID generator. It can generate UUID's using method 1 (MAC address + time) which is good if we need further assurance that UUID's are unique between multiple machines. It includes a JNI library to retrieve the MAC address or a mechanism to specify/generate a random MAC.

The UUID algorithm was intended to be globally unique across all time by including a network address in conjunction with a time stamp. The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination
UUID specification has five versions:-
  • Version 1 (MAC address) :-

Concatenation of the UUID version with the MAC address of the computer that is generating the UUID
  • Version 2 (DCE Security)

  • Version 3 (MD5 hash)

  • Version 4 (random)

  • Version 5 (SHA-1 hash)


Question:-Why UUID is required?

Answer:- Below are the cases for that we can go for UUID generation:-

  • Suppose I would like to use a cryptographically secure primary key for sensitive data in a database - this cannot be predictable and it cannot be generated by the database means I needs that key before the object is saved in the database.
  • Suppose I am working on a distributed application and during sending some data, we have to send some unique identifiers which should be unique for multiple machines.

  •  Suppose during transaction, we want to produce some unique identifiers in order to validate transactions.

  • Another typical example is the value of a cookie used as a session identifier - simply using a series of consecutive integers is generally unacceptable, since one user could easily impersonate another by altering the value of the cookie to some nearby integer.

  • Digital imaging and communication in medicine (DICOM) specifies that all DICOM objects have globally unique identifiers (UIDs). So to fulfill these scenario we can use UUID generator.

  • At last the conclusion is Some of UUID usage are for creating random file names, session id in web application, transaction id and for record’s primary keys in database replacing the sequence or auto generated number.

Famous Globally Unique Identifier generation techniques are as below:-

Technique 1 – Using UUID

When Java 5 is available, the UUID class provides a simple means for generating unique ids. The identifiers generated by UUID are actually universallyunique identifiers

package com.gaurav.uuid;

import java.util.UUID;

public classUUIDGeneratorFirstTechnique {

      publicstatic final void main(String... args) {
            // generate random UUIDs
            UUID generatedUniqueID = UUID.randomUUID();
            captureLogEvent(
                        "GENERATED UNIQUE IDENTIFIER IS : " + generatedUniqueID,
                        generatedUniqueID);

            finalString generatedUUIDWithoutHyphen = UUID.randomUUID().toString()
                        .replaceAll("-", "");
            System.out.println("GENERATED UUID WITHOUT HYPHEN : "
                        + generatedUUIDWithoutHyphen);
      }

      privatestatic void captureLogEvent(Object aObject, UUID uuid) {
            System.out.println(String.valueOf(aObject));
            System.out.println("GENERATED UUID VERSION       = " + uuid.version());
            System.out.println("GENERATED UUID VARIANT       = " + uuid.variant());

      }
}


Result:-

GENERATED UNIQUE IDENTIFIER IS : ec24e9b6-16e8-4075-a005-645ce224f864
GENERATED UUID VERSION       = 4
GENERATED UUID VARIANT       = 2
GENERATED UUID WITHOUT HYPHEN : 23afbb1baba54a3082bd990d979b51a8

 

Technique 2 – Using SecureRandom and MessageDigest

The following program uses SecureRandom and MessageDigest Classes to generate the UUID:
  •       During startup needs to initialize SecureRandom.
  •       when a new identifier is needed, generate a random number using SecureRandom class object
  •       create a MessageDigest class object of the random number
  •       encode the byte[] returned by the MessageDigest into some acceptable textual form
  •       check if the result is already being used ; if it is not already taken, it is suitable as a unique identifier


The MessageDigest class is suitable for generating a "one-way hash" of arbitrary data. A MessageDigest takes any input, and produces a String which :
  •       is of fixed length
  •       MessageDigest does not allow the original input to be easily recovered it's completely difficult. 
  •       MessageDigest does not uniquely identify the input,  however similar input will produce dissimilar message digests
  • MessageDigest can be used as a checksum, for verifying that data has not been altered since its creation. 



Example to generate using SecureRandom and MessageDigest

package com.gaurav.uuid;

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

public classUUIDGeneratorSecondTechnique {
      publicstatic void main(String... args) {
            try{
                  /**

                   * Initializing SecureRandom class, This is a lengthy process so it

                   * should be initialized only upon initialization of the application

                   */

                  SecureRandom secureRandomObject = SecureRandom
                              .getInstance("SHA1PRNG");

                  /** generating a random number using SecureRandom */
                  String randomNum = new Integer(secureRandomObject.nextInt())
                              .toString();

                  /** generating a random number using MessageDigest */
                  MessageDigest messageDigestObject = MessageDigest
                              .getInstance("SHA-1");
                  byte[] resultArray = messageDigestObject.digest(randomNum
                              .getBytes());

                  System.out.println("Random number Generated Using SecureRandom object : " + randomNum);
                  System.out.println("Random number Generated Using Message digest object: " + hexadecimalEncode(resultArray));
            } catch (NoSuchAlgorithmException ex) {
                  System.err.println(ex);
            }
      }


      /**

       *

       * This converts a byte array into a String of hex characters.

       *

       */
      private staticString hexadecimalEncode(byte[] inputDataArray) {
            StringBuilder stringBuilderObject = new StringBuilder();
            char[] digitsInCharArray = { '0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            for(int index = 0; index < inputDataArray.length; ++index) {
                  bytebyteData = inputDataArray[index];
                  stringBuilderObject
                              .append(digitsInCharArray[(byteData & 0xf0) >> 4]);
                  stringBuilderObject.append(digitsInCharArray[byteData & 0x0f]);
            }
            returnstringBuilderObject.toString();
      }

}

Result:-

Random number Generated Using SecureRandom object : -992077914
Random number Generated Using Message digest object: 7384973fc0e0a1c8cf6c53c27384e5e94869dfb2




No comments:

Post a Comment