- Руководство по UUID в Java
- Дальнейшее чтение:
- CharSequence vs. Строка в Java
- Use char[ Массив поверх строки для манипулирования паролями в Java?]
- Руководство по Java String Pool
- 2. Состав
- 2.1. Версия 3 и 5
- 2.2. Версия 4
- 3. Заключение
- Create GUID in Java
- What Is GUID
- Example Code to Generate UUID Using randomUUID() Method
- Example Code to Generate UUID Using UUID constructor and fromString() Method
- Java Unique Number Generator — UUID or GUID with examples
- java.util.UUID class
- Example
- java-uuid-generator maven
- UUID class methods
- Other UUID libraries
Руководство по UUID в Java
UUID (универсальный уникальный идентификатор), также известный как GUID (глобальный уникальный идентификатор), представляетa 128-bit long value that is unique for all practical purposes. Стандартное представление UUID использует шестнадцатеричные цифры (октеты):
123e4567-e89b-12d3-a456-556642440000
UUID состоит из шестнадцатеричных цифр (по 4 символа) и 4 символов «-», составляющихlength equal to 36 characters.
Нулевой UUID — это особая форма UUID, в которой все биты установлены в ноль.
В этой статье мы рассмотрим классUUID в Java.
Дальнейшее чтение:
CharSequence vs. Строка в Java
Узнайте разницу между CharSequence и String.
Use char[ Массив поверх строки для манипулирования паролями в Java?]
Изучите несколько причин, по которым мы не должны использовать строки для хранения паролей, а вместо этого использовать массивы char [].
Руководство по Java String Pool
Узнайте, как JVM оптимизирует объем памяти, выделяемой для хранения строк в пуле строк Java.
2. Состав
123e4567-e89b-42d3-a456-556642440000 xxxxxxxx-xxxx-Bxxx-Axxx-xxxxxxxxxxxx
A представляет собой вариант, который определяет структуру UUID. Все остальные биты в UUID зависят от установки битов в поле варианта. Вариант определяется по 3 старшим значащим битам A:
MSB1 MSB2 MSB3 0 X X reserved (0) 1 0 X current variant (2) 1 1 0 reserved for Microsoft (6) 1 1 1 reserved for future (7)
ЗначениеA в упомянутом UUID — «a». Бинарный эквивалент ‘a ‘(= 10xx) показывает вариант как 2. B представляет версию. Версия в упомянутом UUID (значениеB) — 4.
Java предоставляет методы для получения варианта и версии UUID: __
UUID uuid = UUID.randomUUID(); int variant = uuid.variant(); int version = uuid.version();
Это 5 разных версий для варианта 2 UUID: на основе времени (UUIDv1), безопасности DCE (UUIDv2), на основе имени (UUIDv3 и UUIDv5), случайный (UUIDv4).
Java предоставляет реализацию для v3 и v4, но также предоставляетconstructor для генерации любого типа UUID:
UUID uuid = new UUID(long mostSigBits, long leastSigBits);
2.1. Версия 3 и 5
UUID генерируются с использованием хэша пространства имен и имени. Идентификаторы пространства имен — это UUID, такие как система доменных имен (DNS), идентификаторы объектов (OID), URL-адреса и т. Д.
UUID = hash(NAMESPACE_IDENTIFIER + NAME)
Единственное различие между UUIDv3 и UUIDv5 заключается в алгоритме хеширования — v3 использует MD5 (128 бит), а v5 использует SHA-1 (160 бит).
Проще говоря, мы усекаем результирующий хеш до 128 бит, а затем заменяем 4 бита для версии и 2 бита для варианта.
Давайте сгенерируем UUID типа 3:
String source = namespace + name; byte[] bytes = source.getBytes("UTF-8"); UUID uuid = UUID.nameUUIDFromBytes(bytes);
Java не обеспечивает реализацию для типа 5. Проверьте наш исходный кодrepository для UUIDv5.
2.2. Версия 4
Реализация UUID v4 использует случайные числа в качестве источника. Реализация Java —SecureRandom, которая использует непредсказуемое значение в качестве начального числа для генерации случайных чисел, чтобы уменьшить вероятность конфликтов.
Давайте сгенерируем UUID версии 4:
UUID uuid = UUID.randomUUID();
Давайте сгенерируем уникальный ключ, используя SHA-256 и случайный UUID:
MessageDigest salt = MessageDigest.getInstance("SHA-256"); salt.update(UUID.randomUUID().toString().getBytes("UTF-8")); String digest = bytesToHex(salt.digest());
3. Заключение
И UUIDv3, и UUIDv5 обладают хорошим свойством, заключающимся в том, что разные системы могут генерировать один и тот же UUID, используя одно и то же пространство имен и имя. Они в основном используются для создания иерархических UUID.
Поскольку обе хеш-функции MD5 и SHA1 были повреждены, рекомендуется использовать v5. Если вам просто нужна простая генерация UUID, введите 4 для обычного варианта использования.
И, как всегда, доступен исходный код реализацииover on Github.
Create GUID in Java
- What Is GUID
- Example Code to Generate UUID Using randomUUID() Method
- Example Code to Generate UUID Using UUID constructor and fromString() Method
What Is GUID
GUID is an acronym for Globally Unique Identifier . It is often also referred to Universally Unique Identifiers or UUIDs . There is no genuine difference between the two terms. Technically, these are 128-bit immutable, unique, cryptographically-strong, random numbers. These random numbers are eventually in use for computing purposes. The algorithm to generate such numbers is so complex that it could generate 1,0000,000,000 random numbers per second. These numbers are unlikely to repeat.
We use GUID or UUIDs in software development practices and methodologies, where we would like huge transactions to happen with a unique ID as a primary key that is database keys, component identifiers, and varied transactions.
Example Code to Generate UUID Using randomUUID() Method
package guid; import java.util.UUID; public class CreateGuid public static void main(String[] args) UUID uuid = UUID.randomUUID(); System.out.println("UUID = " + uuid.toString()); > >
In Java language, the UUID class is available after version 1.5. The class is present in the java.util.UUID package. The randomUUID() method is a static factory method to retrieve a type 4 (pseudo-randomly generated) UUID. As the method is a static factory method of the UUID class hence the class name is required to call the method.
The output from the above program seems to be a uniquely generated UUID.
UUID = 70aba303-60d8-4cb5-b3e7-4170c4be5642
Example Code to Generate UUID Using UUID constructor and fromString() Method
In the below program, the UUID class constructor is used to generate a UUID. The constructor takes two parameters, mostSignificantBits and leastSignificantBits .
The mostSignificantBits is for the most significant 64 bits of the UUID, and the leastSignificantBits is for the least significant 64 bits.
The fromString() method is a static factory method that creates a UUID from the string standard representation. The above method takes String as a parameter. So over the uuid object, the toString() method is called in the inline function.
The fromString method throws IllegalArgumentException if the name does not conform to the string representation described in the toString method.
package guid; import java.util.UUID; public class GenerateGuidUsingConstructor public static void main(String[] args) UUID uuid = new UUID(24, 02); System.out.println(UUID.fromString(uuid.toString())); > >
Below is the output of the UUID generated from the constructor.
00000000-0000-0018-0000-000000000002
Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.
Java Unique Number Generator — UUID or GUID with examples
The universally unique identifier is a unique string to represent information in software applications.
UUID — universally unique identifier,
GUID globally unique identifier,
The difference between UUID and GUID, Both are returning 126 bits,
GUID is Microsoft’s implementation of UUID functionality. Both generate 16 bytes hexadecimal separated by a hyphen in four groups.
- Used to represent a primary key in a database table
- can be used as Session ID in web applications, Transaction Id in enterprise applications.
- Can also be used as a unique identifier for doing CRUD operations in REST API applications.
- Represents to identify big data spread across multiple servers.
- Naming static resources for storing and retrieving files.
Java provides java.util.UUID class for providing UUID implementation in java
java.util.UUID class
- Generates 128 bit or 16 bytes that contain hexadecimal values
- Implements Serializable, Comparable interfaces
- Extends Object class.
There are multiple variants for creating a UUID. It has methods for operating the Leach-Salz variant.
However, We can create multiple variants using the constructor.
Constructor:
UUID(long mostSigBits, long leastSigBits)
It has only one constructor which takes two parameters to create a new UUID mostSigBits — most significant bits 64 bits of UUID
leastSigBits — least significant 64 bits of UUID
- Version 1 represents time-based — UUID V1
- Version 2 represents DCE security — UUID V2
- Version 3 represents name-based — UUID V3
- Version 4 represents Random generated — — UUID V4
Example
The below example generates a UUID V4 string in java.
import java.util.UUID; public class UUIDDemo public static void main(String[] args) UUID uuid = UUID.randomUUID(); String uuidString = uuid.toString(); System.out.println(uuid.variant()); // 2 System.out.println(uuid.version()); // 4 System.out.println(uuidString); //3d795ac3-2cea-4ed2-92d8-3d71a2539cf2 > >
java-uuid-generator maven
In maven applications, java-uuid-generator is a dependency from com.fasterxml.UUID. It is a java library for generating UUID with all versions.
dependency> groupId>com.fasterxml.uuidgroupId> artifactId>java-uuid-generatorartifactId> version>3.1.5version> dependency>
- UUID V1 Generation using timebase generator
- UUID V3 Generation using UUID.nameUUIDFromBytes method as well as name-based
- UUID V4 Generation using randomBasedGenerator
- UUID V5 Generation using SHA digester
import java.util.UUID; import com.fasterxml.uuid.Generators; public class HelloWorld public static void main(String[] args) // UUID V1 generation UUID v1 = Generators.timeBasedGenerator().generate(); System.out.println(«UUID V1 value: « + v1.toString()); System.out.println(«version : « + v1.version()); System.out.println(«variant : « + v1.variant()); // UUID V3 generation // create byte array and initialize it byte[] byteArray = 0, 1, 4 >; // Create uuid from byte array UUID v3 = UUID.nameUUIDFromBytes(byteArray); System.out.println(«UUID V4 value: « + v3.toString()); System.out.println(«version : « + v3.version()); System.out.println(«variant : « + v3.variant()); // UUID V4 generation UUID v4 = Generators.randomBasedGenerator().generate(); System.out.println(«UUID V4 value: « + v4.toString()); System.out.println(«version : « + v4.version()); System.out.println(«variant : « + v4.variant()); // UUID V5 generation UUID v5 = Generators.nameBasedGenerator().generate(«cloudhadoop.com»); System.out.println(«UUID V5 value: « + v5.toString()); System.out.println(«version : « + v5.version()); System.out.println(«variant : « + v5.variant()); > >
The output of the above program code is
UUID V1 value: 04272c28-e69d-11e8-be73-df7930994371 version : 1 variant : 2 UUID V4 value: be489ef3-af30-3d20-b50a-5c504ecc5294 version : 3 variant : 2 UUID V4 value: 1c4e3ff8-bf58-4081-8e3f-f8bf58908109 version : 4 variant : 2 UUID V5 value: cdecd331-e6c2-5e7f-ad1d-3ee766052560 version : 5 variant : 2
UUID class provides fromString() method which generates UUID from a given string. This is an example for Converting String to UUID. This method throws Exception in thread “main” java.lang.IllegalArgumentException: Invalid UUID string: 150e064ff8d6, if string is not 16 bytes in length
import java.util.UUID; public class fromStringExample public static void main(String[] args) UUID uuid = UUID.fromString(«d4578015-0e06-4ff8-9780-150e064ff8d6»); System.out.println(«UUID value: « + uuid.toString()); System.out.println(«version : « + uuid.version()); System.out.println(«variant : « + uuid.variant()); > >
The output of the above code is
UUID value: d4578015-0e06-4ff8-9780-150e064ff8d6 version : 4 variant : 2 UUID class methods
UUID class methods
- clockSequence — this method returns clock sequence for given UUID. It throws Exception in thread “main” java.lang.UnsupportedOperationException: Not a time-based UUID.if it is not time-based UUID version
- getLeastSignificantBits — This method returns least significant 64 bits of given UUID
- getMostSignificantBits() — This method returns m significant 64 bits of given UUID
- nameUUIDFromBytes(bytearray) — this method returns UUID V3 for given byte array
- node()— This method return node value of given UUID
- timestamp() — This return timestamp of given UUID
- randomUUID — This static method generates random UUID