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());