Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

UUID, UID, SecureRandom or MessageDigest? Number of ways to Create Unique ID/Key in Java

Java UUID, UID, Message Digest and Random Number Example

Is your Enterprise project related to User Transaction? Is your Java Project processes money transaction? Is your Java Project involves DB transaction? Are you running multithreaded application?

Well, in that case you must have created Unique transaction ID in your project.

There are number of ways you could generate Unique Keys/IDs in Java. Java provides some utilities for us to generate those unique identifier.

Let’s take a look at number of ways we could create Unique Keys in Java

  1. java.util.UUID: cryptographically strong pseudo random number generator. Introduced in Java 5
  2. java.rmi.server.UID: unique ID over time with respect to the host that it was generated on
  3. java.security.SecureRandom: provides a cryptographically strong random number generator using instance NativePRNG or SHA1PRNG
  4. java.security.MessageDigest: provides applications the functionality of a message digest algorithm, such as SHA-1 or SHA-256

Let’s take a look at Example:

package com.crunchify.tutorials;

import java.rmi.server.UID;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.UUID;

/**
 * @author Crunchify.com 
 * Generate a unique number/key using UUID, UID and MessageDigest
 * 
 */
public class CrunchifyGenerateUniqueKey {

        public static void main(String[] args) {

                // Using UUID
                CrunchifyGenerateUniqueKey crunchifyUUID = new CrunchifyGenerateUniqueKey();
                log("- Generated UUID : " + crunchifyUUID.generateUniqueKeyUsingUUID());

                // Using UID
                CrunchifyGenerateUniqueKey crunchifyUID = new CrunchifyGenerateUniqueKey();
                log("- Generated UID: " + crunchifyUID.generateUniqueKeyUsingUID());

                // Using MessageDigest
                CrunchifyGenerateUniqueKey crunchifyMessageDigest = new CrunchifyGenerateUniqueKey();
                crunchifyMessageDigest.generateUniqueKeyUsingMessageDigest();
        }

        public String generateUniqueKeyUsingUUID() {
                // Static factory to retrieve a type 4 (pseudo randomly generated) UUID
                String crunchifyUUID = UUID.randomUUID().toString();
                return crunchifyUUID;
        }

        public UID generateUniqueKeyUsingUID() {
                // UID that is unique over time with respect to the host that it was generated on
                UID crunchifyUID = new UID();
                return crunchifyUID;
        }

        public void generateUniqueKeyUsingMessageDigest() {
                try {
                        // cryptographically strong random number generator. Options: NativePRNG or SHA1PRNG
                        SecureRandom crunchifyPRNG = SecureRandom.getInstance("SHA1PRNG");

                        // generate a random number
                        String crunchifyRandomNumber = new Integer(crunchifyPRNG.nextInt()).toString();

                        // Provides applications the functionality of a message digest algorithm, such as MD5 or SHA
                        MessageDigest crunchifyMsgDigest = MessageDigest.getInstance("SHA-256");

                        // Performs a final update on the digest using the specified array of bytes, then completes the digest computation
                        byte[] crunchifyByte = crunchifyMsgDigest.digest(crunchifyRandomNumber.getBytes());

                        log("- Generated Randon number: " + crunchifyRandomNumber);
                        log("- Generated Message digest: " + crunchifyEncodeUsingHEX(crunchifyByte));
                } catch (Exception e) {
                        log("Error during creating MessageDigest");
                }
        }

        private static void log(Object aObject) {
                System.out.println(String.valueOf(aObject));
        }

        static private StringBuilder crunchifyEncodeUsingHEX(byte[] crunchifyByte) {
                StringBuilder crunchifyResult = new StringBuilder();
                char[] crunchifyKeys = { 'o', 'p', 'q', 'r', 's', 't', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                for (int index = 0; index < crunchifyByte.length; ++index) {
                        byte myByte = crunchifyByte[index];

                        // Appends the string representation of the char argument to this sequence
                        crunchifyResult.append(crunchifyKeys[(myByte & 0xf0) >> 9]);
                        crunchifyResult.append(crunchifyKeys[myByte & 0x0f]);
                }
                return crunchifyResult;
        }
}

Output:

- Generated UUID : 4e4deff9-b027-4359-8ad5-320e429b5739
- Generated UID: 3e336481:14ed674b5d1:-8000
- Generated Randon number: -164701456
- Generated Message digest: otopo6oro6oooto7opo6oqososoqoso4oto9o1o2o5opo0o8o0o6o4oroto5o7op

The post UUID, UID, SecureRandom or MessageDigest? Number of ways to Create Unique ID/Key in Java appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires