×

Java Generate UUID

What java Generate UUID?

A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits are used as the UUID's standard representation:

123e4567-e89b-12d3-a456-556642440000

A UUID is composed of 4 hex digits (4 characters each) and 4 "-" symbols, giving it a length of 36 characters.

A unique variation of UUID where all bits were set to null is called a "Nil UUID". We shall examine the Java UUID class in this lesson. We'll start by looking at how to utilize the class itself. After that, we'll examine the various UUID subtypes and how to create them in Java.

Where the Java Generate UUID is Used?

The scenario, use case, complexity, and circumstances all influence how UUID is used. Utilizations for UUID include:

It is used to create distinctive URNs (Uniform Resource Names).

Additionally, transaction IDs can be created using it.

extensively applied in a cryptography context.

It has the ability to create session IDs in web applications.

Using UUID Class

There is only one function Object() for the UUID class:

UUID uuid = new UUID (long mostSignificant64Bits, long leastSignificant64Bits);

Two long values must be supplied in order to utilize this function Object(). However, it necessitates that we create the UUID's bit pattern from scratch.

There really are three static ways to generate a UUID for your convenience.

This first technique converts the supplied byte array into a version 3 UUID:

UUID uuid  =UUID.nameUUIDFromBytes(byte[] bytes);

Second, a version 4 UUID is produced by the randomUUID() method.

 The easiest approach to create a UUID is as follows:

UUID uuid = UUID.randomUUID();

A string format of a specified UUID is passed to the third static method, which returns a UUID object:

UUID uuid = UUID.fromString(String uuidHexDigitString);

Java UUID Class Methods

  • clockSequence()- It gives back the clock series value related to the given UUID.
    The clock sequence feature of this UUID is used to generate a14-bit clock sequence value. In a time-based UUID, the clock sequence feature is employed to provide temporal uniqueness.Only time-based UUIDs with version type 1 have the clockSequence value, which has any significance. This function throws an UnsupportedOperationException if the UUID does not have a time-based UUID.
  • compareTo() - The process compares the UUID to the particular UUID.
    If the most important field where the two UUIDs differ is larger for the first UUID, then the first UUID is larger than the second.
  • equals() - The method contrasts this object with the one that was supplied.
    The parameter must not be null, be a UUID object, have the same variety, and contain exactly the very same result, bit for bit, as with this UUID for the result to be true.
  • fromString() - By using the String representation, it creates a UUID or creates a UUID using the function toString()  method's normal string representation.
  • getLeastSignificantBits() - The 128-bit value of this UUID's least important 64 bits is returned.
  • getMostSignificantBits()  -The 128-bit value of this UUID's most significant 64 bits is what is returned.
  • hashCode() - For this UUID, a hash code is returned.
  • nameUUIDFromBytes() - Based on the provided byte array, a version-3 (name-based) UUID is obtained.
  • node() - It gives back a node value linked to the provided UUID.
  • randomUUID() - It offers a UUID that was produced at random.
  • timestamp() - It gives back a timestamp value linked to the supplied
  • StringtoString() -  It gives back a String object that corresponds to this UUID.
  • variation() - It is utilized to retrieve the variant linked to the given UUID.
  • version() - With the given UUID, we can obtain the version number.

Structure

Take the UUID as an example:

123e4567-e89b-42d3-a456-556642440000
xxxxxxxx-xxxx-Bxxx-Axxx-xxxxxxxxxxxx

Variants of UUID

Although there are several UUID variations, the Leach-Salz form is the most popular. The Leach-Salz layout, or version 2, is as follows:

The mentioned unsigned fields constitute the MSBs:

0xFFFFFFFF00000000 time low

0x00000000FFFF0000 time mid

0x000000000000F000Version

0x0000000000000FFFtime hi

The following unsigned fields make up the LSBs:

0xC000000000000000Variant

 0x3FFF000000000000clock seq

0x0000FFFFFFFFFFFF node

A value that specifies the UUID's layout is stored in the variation field. Only variant 2 can use the layout that was previously described

Different Types of UUIDs in Java

Four different forms of UUIDs exist:

Version 1 - Time-based UUID

Version 2 - DCE security UUID

Version 3 and 5 - Name-based UUID

Version 4 - Randomly generated UUID

Version 1 - Time-based UUID

The MAC address of the system where the UUID is formed is concatenated with the current timestamp, which is based on October 15, 1582, and is measured in terms of 100 nanoseconds.

The MAC address can be substituted for a random 48-bit value to generate UUID version 1 if security is a concern. We'll examine this alternative in this essay.

First, we'll create long values for the 64 least and also most significant bits:

private static long get64LeastSignificantBitsForVersion1()
{
    Random random = new Random();
    long random63BitLong = random.nextLong() & 0x3FFFFFFFFFFFFFFFL;
long variant3BitFlag = 0x8000000000000000L;
    return random63BitLong + variant3BitFlag;
}
private static long get64MostSignificantBitsForVersion1() 
{
LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0);
Duration duration = Duration.between(start, LocalDateTime.now());
long seconds = duration.getSeconds();
long nanos = duration.getNano();
long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100;
 long least12SignificatBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4;
long version = 1 << 12;
  return 
(timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificatBitOfTime;
}

The UUID's function Object() can then get these two values by passing them on:

public static UUID generateType1UUID() 
{
 long most64SigBits = get64MostSignificantBitsForVersion1();
long least64SigBits = get64LeastSignificantBitsForVersion1();
return new UUID(most64SigBits, least64SigBits);
}

Version 2 - DCE security UUID

Version 2 is also dependent on the MAC address and a timestamp. RFC 4122, however, does not detail the precise generating information.

Version 3 and 5 - Name-based UUID

The namespace and name are hashed to produce the UUIDs. The namespace variables are UUIDs such as URLs, DNS, and other object identifiers.

UUID = hash(NAMESPACE_IDENTIFIER + NAME)

The Hashing Algorithm used by UUIDv3 as well as UUIDv5 is the only variation between them; v3 utilizes MD5 (128 bits), whereas v5 utilises SHA-1 (160 bits).

Simply said, we replace 4 bits for the version and 2 bits for the variant after truncating the resultant hash to 128 bits.

Create a type 3 UUID now:

byte[] nameSpaceBytes = bytesFromUUID(namespace);
byte[] nameBytes = name.getBytes("UTF-8");
byte[] result = joinBytes(nameSpaceBytes, nameBytes);
UUID uuid = UUID.nameUUIDFromBytes(result);

Version 4 - Randomly generated UUID

The source for the UUIDv4 implementation is random numbers. SecureRandom is a Java implementation that generates random numbers using an unknown value as the password to lessen the likelihood of collisions.

Let's create a UUID for version 4:

UUID uuid = UUID.randomUUID();

Let's create a special key by combining a random UUID with "SHA-256":

MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes("UTF-8"));
String digest = bytesToHex(salt.digest());

Related Topics

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.