Java random uuid generator

Java UUID Generator Example

Learn what is UUID and it’s versions and variants. Learn to generate UUID in Java using UUID.randomUUID() API. Also learn to generate version 5 UUID in Java.

UUID (Universally Unique IDentifier), also known as GUID (Globally Unique IDentifier) is 128 bits long identifier that is unique across both space and time, with respect to the space of all other UUIDs. It requires no central registration process. As a result, generation on demand can be completely automated, and used for a variety of purposes.

To understand how unique is a UUID, you should know that UUID generation algorithms support very high allocation rates of up to 10 million per second per machine if necessary, so that they could even be used as transaction IDs.

We can apply sorting, ordering and we can store them in databases. It makes it useful in programming in general.

Since UUIDs are unique and persistent, they make excellent Uniform Resource Names (URNs) with lowest mining cost in comparison to other alternatives.

Читайте также:  Рамка вокруг таблицы

The nil UUID is special form of UUID that is specified to have all 128 bits set to zero.

Do not assume that UUIDs are hard to guess; they should not be used as security capabilities. A predictable random number source will exacerbate the situation. Humans do not have the ability to easily check the integrity of a UUID by simply glancing at it.

A typical UID is displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and 4 hyphens).

Here ‘M’ indicate the UUID version and ‘N’ indicate the UUID variant.

  • The variant field contains a value which identifies the layout of the UUID.
  • The version field holds a value that describes the type of this UUID. There are five different basic types of UUIDs.
    1. Time-Based UUID (Version 1) – generated from a time and a node id
    2. DCE (Distributed Computing Environment) security (Version 2) – generated from an identifier (usually a group or user id), time, and a node id
    3. Name-based (Version 3) – generated by MD5 (128 bits) hashing of a namespace identifier and name
    4. Randomly generated UUIDs (Version 4) – generated using a random or pseudo-random number
    5. Name-based using SHA-1 hashing (Version 5) Recommended – generated by SHA-1 (160 bits) hashing of a namespace identifier and name. Java does not provide its implementation. We shall create our own.

3.1. UUID.randomUUID() – Version 4

Default API randomUUID() is a static factory to retrieve a type 4 (pseudo randomly generated) UUID. It is good enough for most of the usecases.

UUID uuid = UUID.randomUUID(); System.out.println(uuid); System.out.println(uuid.variant()); //2 System.out.println(uuid.version()); //4
17e3338d-344b-403c-8a87-f7d8006d6e33 2 4

3.2. Generate Version 5 UUID

Java does not provide inbuilt API to generate version 5 UUID, so we have to create our own implementation. Below is one such implementation. (Ref).

import java.nio.ByteOrder; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; public class UUID5 < public static UUID fromUTF8(String name) < return fromBytes(name.getBytes(Charset.forName("UTF-8"))); >private static UUID fromBytes(byte[] name) < if (name == null) < throw new NullPointerException("name == null"); >try < MessageDigest md = MessageDigest.getInstance("SHA-1"); return makeUUID(md.digest(name), 5); >catch (NoSuchAlgorithmException e) < throw new AssertionError(e); >> private static UUID makeUUID(byte[] hash, int version) < long msb = peekLong(hash, 0, ByteOrder.BIG_ENDIAN); long lsb = peekLong(hash, 8, ByteOrder.BIG_ENDIAN); // Set the version field msb &= ~(0xfL private static long peekLong(final byte[] src, final int offset, final ByteOrder order) < long ans = 0; if (order == ByteOrder.BIG_ENDIAN) < for (int i = offset; i < offset + 8; i += 1) < ans > else < for (int i = offset + 7; i >= offset; i -= 1) < ans > return ans; > >
UUID uuid = UUID5.fromUTF8("954aac7d-47b2-5975-9a80-37eeed186527"); System.out.println(uuid); System.out.println(uuid.variant()); System.out.println(uuid.version());
d1d16b54-9757-5743-86fa-9ffe3b937d78 2 5

Drop me your questions related to generating UUID in Java.

Источник

Generate a UUID in Java

Java is one of the most popular programming languages in the world!

Since its humble beginnings at Sun Microsystems in 1991, Java has come to dominate enterprise backend software, run the majority of smart phones (Android), and be used extensively on desktop computers in apps such as LibreOffice and Minecraft.

How to Generate a UUID in Java

The Java language has built-in support for generating Version 4 UUIDs. Here’s an example of how you can create a UUID in Java code.

import java.util.UUID;
class MyUuidApp
public static void main(String[] args)
UUID uuid = UUID.randomUUID();
String uuidAsString = uuid.toString();
System.out.println("Your UUID is: " + uuidAsString);
>
>

Explanation

  • On line #1, we import the UUID class. This class is part of the standard Java JDK. No 3rd party libraries are required.
  • On line #5, the UUID class’ static method, randomUUID() , is used to generate a new, version 4 UUID. The generated UUID object is stored in the variable, uuid .
  • Line #6 converts the uuid object into a Java String by calling its toString() method. The String representation of a UUID looks like a standard UUID (i.e. f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454 ). If you’re going to store the UUID in a file, database or model property, or send it via an API call to a different application, you’ll almost always need the String representation of the uuid object, rather than the uuid object itself.
  • The output from line #8 will be something like:
Your UUID is: f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454

Convert from a String to a UUID in Java

Although it’s rare, in some circumstances you might need to convert from a String representation of a UUID (like the one from line #6 above) back into an instance of UUID .

Java’s UUID class provides for this scenario with the static method, fromString(String) . You can call this method like this:

import java.util.UUID;
class MyUuidApp
public static void main(String[] args)
UUID uuid = UUID.randomUUID();
String uuidAsString = uuid.toString();
UUID sameUuid = UUID.fromString(uuidAsString);
assert sameUuid.equals(uuid);
>
>

Explanation

  • Line #8 shows converting the string representation of a UUID into a Java UUID instance ( sameUuid ) using the fromString(String) method.
  • Line #9 is included to show that the 2 UUID instances are equal.

How can we improve this page? Let us know!

Источник

How to generate random UUID in Java

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

What is UUID?

The full form of UUID is Universally Unique Identifier. A UUID represents a 128-bit value that is unique. The standard representation of UUID uses hex digits.

UUID in Java

The UUID class in the java.util package bundles the method to generate random UUID.

There are four different versions of UUID. They are as follows:

  1. Time-based UUID
  2. DCE security UUID
  3. Name-based UUID
  4. Randomly generated UUID

This shot covers how to generate a randomly generated UUID.

Randomly generated UUID

The randomly generated UUID uses a random number as the source to generate the UUID.

In Java, the randomUUID() static method is used to generate a random UUID. The method internally uses SecureRandom class, which provides a cryptographically strong random number generator.

Every UUID is associated with a version number. The version number describes how the UUID was generated. The .version() method is used to get the version of the generated UUID.

Version number in java How the UUID was generated
1 Time-based UUID
2 DCE security UUID
3 Name-based UUID
4 Randomly generated UUID

Источник

Generate UUID in Java: Best Implementation

Today we will be looking at how we can generate UUID in Java. Using no additional external libraries.

You must have already known that there are more than one UUID versions. So we are going to cover it version by topic.

But today prior to version 4 are not in use anymore so let us look at version 4 and version 5.

Generate UUID4 in Java

This version of UUID is the most widely used. Here is the code for generating UUID version 4.

Generating random UUID

import java.util.UUID; public class UuidHelper < public static String getUuid4() < return UUID.randomUUID().toString(); > >Code language: Java (java)

If you did not understand what we did above. Let me provide you a little context. We have a UUID class that has .randomUUID() . It will provide us an instance of UUID class.

To convert it to string we just have to use the .toString() method.

Generating UUID from string

If you have a string and you want to instantiate a UUID instance. You should use .fromString() method like below.

The use case for this is really rare. But if you want to you can use the following code.

import java.util.UUID; public class UuidHelper < public static UUID getUuid4(String uuid) < return UUID.fromString(uuid); > >Code language: JavaScript (javascript)

If the UUID is invalid then it will throw an IllegalArgumentException .

Generate UUID5 in Java

UUID5 is very different from UUID4 in implementation. It is because UUID5 makes us define namespace for usage.

Because of this we have to borrow the implementation from exiting utilities. I have borrowed code from Apache Commons.

Since this is not an official implementation. We will not be doing things as we have done above. We will just use the UUID5 string representation.

And if you are wondering if you need version 5. The simple answer is you don’t. But anyway here is the implementation.

 import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.UUID; public class Uuid5 < private static final Charset UTF8 = Charset.forName("UTF-8"); public static final UUID NAMESPACE_DNS = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8"); public static final UUID NAMESPACE_URL = UUID.fromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8"); public static final UUID NAMESPACE_OID = UUID.fromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8"); public static final UUID NAMESPACE_X500 = UUID.fromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8"); public static UUID nameUUIDFromNamespaceAndString(UUID namespace, String name) < return nameUUIDFromNamespaceAndBytes(namespace, Objects.requireNonNull(name, "name == null").getBytes(UTF8)); > public static UUID nameUUIDFromNamespaceAndBytes(UUID namespace, byte[] name) < MessageDigest md; try < md = MessageDigest.getInstance("SHA-1"); > catch (NoSuchAlgorithmException nsae) < throw new InternalError("SHA-1 not supported"); > md.update(toBytes(Objects.requireNonNull(namespace, "namespace is null"))); md.update(Objects.requireNonNull(name, "name is null")); byte[] sha1Bytes = md.digest(); sha1Bytes[6] &= 0x0f; /* clear version */ sha1Bytes[6] |= 0x50; /* set to version 5 */ sha1Bytes[8] &= 0x3f; /* clear variant */ sha1Bytes[8] |= 0x80; /* set to IETF variant */ return fromBytes(sha1Bytes); > private static UUID fromBytes(byte[] data) < // Based on the private UUID(bytes[]) constructor long msb = 0; long lsb = 0; assert data.length >= 16; for (int i = 0; i < 8; i++) msb = (msb 8) | (data[i] & 0xff); for (int i = 8; i < 16; i++) lsb = (lsb 8) | (data[i] & 0xff); return new UUID(msb, lsb); > private static byte[] toBytes(UUID uuid) < // inverted logic of fromBytes() byte[] out = new byte[16]; long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); for (int i = 0; i < 8; i++) out[i] = (byte) ((msb >> ((7 - i) * 8)) & 0xff); for (int i = 8; i < 16; i++) out[i] = (byte) ((lsb >> ((15 - i) * 8)) & 0xff); return out; > > Code language: Java (java)

Also here is a simple usage for the implementation above.

class UuidTest < public void testUuid5() < UUID test = Uuid5.nameUUIDFromNamespaceAndString(Uuid5.NAMESPACE_URL, "techenum.com"); System.out.println(test); System.out.println(test.version()); > >Code language: Java (java)

So that’s how we generate UUID in Java.

Recommended

Источник

Java random uuid generator

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью