Generating Unique Identifiers in java

Subscribe for New Posts


There are numerous applications which require unique identification numbers at every fixed interval so that the small tasks or subroutines can be idetified uniquely. For instance, transaction ids, token numbers, SSIDs(Service Set identifiers),etc. needs to be unique. There are many ways of generating unique identifiers in java but today let us discuss some of the best and frequently used techniques. We are going to discuss three major ways of generating unique ids:

Generating Unique Identifiers using UID class

The first way is to UID class which is inside java.rmi.server package. The Serializable identifiers generated by this class are unique on the host on which they are generated. Although, there are some prerequisites:

Example

import java.rmi.server.UID;
public class GenerateIds{
    public static void main(String ...args){
        for(int i = 0; i < 5; i++){
            UID uid = new UID();
            System.out.println("User Id" + (i + 1) + ": " + uid);
        }
    }
}
/*
User Id1: -7d12ded1:1700ef1a2f9:-8000
User Id2: -7d12ded1:1700ef1a2f9:-7fff
User Id3: -7d12ded1:1700ef1a2f9:-7ffe
User Id4: -7d12ded1:1700ef1a2f9:-7ffd
User Id5: -7d12ded1:1700ef1a2f9:-7ffc
*/

NOTE 1: In order to construct a UID that is globally unique just pair it with InetAddress.

NOTE 2: These identifiers are not the secure identifiers. If you know one you can easily guess the others.

Generating Unique Identifiers using Secure Random and MessageDigest Classes

This method of generating unique identifiers is a little lengthy and laborious. So in order to make things simpler let us break down this method into smaller tasks.

  1. Initialize SecureRandom
    SecureRandom secureRandom = new SecureRandom("DRBG");
    
    • For Set of available alogorithms(in the above case DRBG) read here
  2. When a new Identifier is needed; generate a random number using the above SecureRandom instance.
    String randN = Integer.valueOf(secureRandom.nextInt()).toString();
    
  3. Create the digest of the random number generated above.
    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
    byte[] res =  sha256.digest(randN.getBytes());
    
  4. Finally encode the byte returned by digest into some acceptable form.
    • You can use HEXENCODE
      static private String hexEncode(byte[] input){
       StringBuilder result = new StringBuilder();
       char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
       for (int idx = 0; idx < input.length; ++idx) {
       byte b = input[idx];
       result.append(digits[ (b&0xf0) >> 4 ]);
       result.append(digits[ b&0x0f]);
       }
       return result.toString();
      }
      }
      
    • You can also use the popular one i.e. BASE64Encode
      import java.util.Base64;
      static private String base64Encodeer(byte[] input){
       // Getting encoder  
       Base64.Encoder encoder = Base64.getEncoder();
       return encoder.encode(input).toString(); 
      }
      

To sum up the code at one place:

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

public final class GenerateId {

  public static void main (String[] args) {
    try {
    // Step 1
      SecureRandom secureRandom = SecureRandom.getInstance("DRBG");

      // Step 2
      String randN = Integer.valueOf(secureRandom.nextInt()).toString();

      // Step 3
      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] res =  sha256.digest(randN.getBytes());

      System.out.println("Random number: " + randN);
    //   Step 4
      System.out.println("Message digest: " + hexEncode(res));
    }
    catch (NoSuchAlgorithmException ex) {
      System.err.println(ex);
    }
  }

  static private String hexEncode(byte[] input){
    StringBuilder result = new StringBuilder();
    char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
    for (int idx = 0; idx < input.length; ++idx) {
      byte b = input[idx];
      result.append(digits[ (b&0xf0) >> 4 ]);
      result.append(digits[ b&0x0f]);
    }
    return result.toString();
  }

  static private String base64Encoder(byte[] input){
    // Getting encoder  
    Base64.Encoder encoder = Base64.getEncoder();
    return encoder.encode(input).toString(); 
  }
} 

Generating Unique Identifiers using UUID

It is always a good practice to save the best for the last:jack_o_lantern:. As the full form suggests, this method is the most easiest and most preferred way of generating unique Identifiers globally.

import java.util.UUID;
public static void main(String[] args){
    //generating random UUIDs(Returns object)
    UUID id1 = UUID.randomUUID();
    UUID id2 = UUID.randomUUID();
    logger("UUID One: " + id1);
    logger("UUID Two: " + id2);
}
public static void logger(Object obj){
    System.out.println(String.valueOf(obj));
}