×

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

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.