What is java.util.UUID, how do randomUUID and nameUUIDFromBytes produce their bits, and when is a UUID a poor database key or secret token?
answer
- 128 bits, a few of them fixed
- strong randomness versus a hash
- same name, same value
- inserts land at random index positions
- possession must not grant access
basics
~20 sjava.util.UUID is an immutable 128-bit identifier. randomUUID fills it from SecureRandom (version 4); nameUUIDFromBytes hashes your bytes with MD5 (version 3). Random keys hurt index locality and take twice a sequence's size, and UUIDs should not serve as secret tokens.
solid answer
~50 s`java.util.UUID` is an immutable 128-bit identifier whose version field records how it was made. `randomUUID()` gives version 4: 16 bytes from `SecureRandom` with the version and variant bits overwritten, leaving 122 random bits. `nameUUIDFromBytes` gives version 3: an MD5 hash of your bytes with the same bits overwritten, so equal input gives an equal UUID. As a database key a UUID needs no coordination, but it takes 16 bytes against 8 for a `long` sequence, and version 4's random order scatters B-tree inserts. A single database is usually better off with a sequence, and version 7, which `UUID.ofEpochMillis` creates since Java 26, suits an application that must generate its own keys. As a secret, RFC 9562 says UUIDs must not be security capabilities, and a name-based one can be computed by anyone who knows the input, so I generate tokens with `SecureRandom` directly.
code
java · 25 linesimport java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.UUID;
public class UuidDemo {
public static void main(String[] args) {
System.out.println(UUID.randomUUID().version()); // 4
byte[] name = "user:alice".getBytes(StandardCharsets.UTF_8);
UUID named = UUID.nameUUIDFromBytes(name);
System.out.println(named.version()); // 3
System.out.println(named.equals(UUID.nameUUIDFromBytes(name))); // true
// Java 26 and later
UUID timed = UUID.ofEpochMillis(1_800_000_000_000L);
System.out.println(timed.version()); // 7
System.out.println(timed.getMostSignificantBits() >>> 16); // 1800000000000
// A secret token, built without UUID
byte[] secret = new byte[32];
new SecureRandom().nextBytes(secret);
System.out.println(Base64.getUrlEncoder().withoutPadding().encodeToString(secret));
}
}go deeper
Recall that a UUID is a 128-bit value, that randomUUID gives version 4 and nameUUIDFromBytes gives version 3, and that the second returns the same value for the same bytes.
Explain the bits: SecureRandom or MD5 fills all 128, then version and variant bits are overwritten, leaving 122 random bits in version 4. Add that ofEpochMillis creates version 7 from Java 26.
Show the judgment: a sequence for a single database, version 7 when the application must generate keys, binary storage over text, and a dedicated SecureRandom token rather than any UUID when possession grants access.
Weigh a key standard for a whole organisation: independent generation and safe merging against wider indexes, exposed creation times against exposed row counts, and what the choice costs on Java 25 LTS, which lacks the factory.
## What java.util.UUID is `java.util.UUID` is an immutable, final class representing a 128-bit **universally unique identifier**, held in two private `long` fields. Its text form has 32 hex digits and 4 hyphens, such as `01a3185c-5000-75dc-98cf-536d5dd25f13`. Four bits hold the **version**, which says how the value was generated, and for the standard layout two more hold the **variant**. `version()` and `variant()` read them back. The format is specified by RFC 9562. The reason to use one is that separate generators can create values with no coordination, and for the random versions a clash is not a realistic concern. ## How each factory produces its bits | Factory | Version | Source of the bits | Equal input, equal output? | |---|---|---|---| | `UUID.randomUUID()` | 4 | `SecureRandom`: 122 random bits | Takes no input; each value is almost certainly different | | `UUID.nameUUIDFromBytes(bytes)` | 3 | MD5 hash of `bytes` | Yes | | `UUID.ofEpochMillis(millis)` | 7 | Your 48-bit timestamp plus 74 `SecureRandom` bits | No: the random bits differ | `randomUUID()` fills 16 bytes from a shared private `SecureRandom`, then overwrites the version bits in byte 6 and the variant bits in byte 8. Removing those 4 and 2 bits from 128 leaves 122 random bits. `nameUUIDFromBytes` hashes the array with MD5 and overwrites the same positions. Nothing random is involved, so equal bytes give an equal UUID on any machine, which suits a stable id derived from a natural key. Two cautions apply: - It hashes only the bytes you pass, whereas RFC 9562 defines version 3 over a namespace ID concatenated with the name. Add namespace bytes yourself to keep separate namespaces apart. - The RFC says version 5, which uses SHA-1, SHOULD be used instead of version 3 where possible, and `UUID` has no version 5 factory. `ofEpochMillis(long)` arrived in **Java 26**, so Java 25 LTS has no version 7 factory. It rejects a negative timestamp or one beyond 48 bits with `IllegalArgumentException`. ## As a database key | Key | Size | Needs the database to issue it? | Index locality | What it reveals | |---|---|---|---|---| | `long` sequence | 8 bytes | Yes, or a reserved block of values | Good: new keys go at one end | Row counts, and neighbouring ids are guessable | | Version 4 | 16 bytes | No | Poor: random positions | Nothing about the row | | Version 7 | 16 bytes | No | Good: roughly time-ordered | Creation time | A UUID is a poor fit in these situations: - **One database issuing its own keys.** A sequence is half the size and inserts in order, while the UUID buys independence nothing uses. Every index that stores the key pays the extra width again. - **Version 4 on a large, insert-heavy B-tree index.** RFC 9562 says versions that are not time ordered "have poor database-index locality": new values go in at random locations, and the effect on B-trees "can be dramatic". - **Stored as text.** The RFC notes that text takes 288 bits for a 128-bit value and says UUIDs SHOULD be stored as binary where feasible. It earns its place when the application must create the id before the insert, when rows from several databases must merge, or when public ids must not reveal row counts. Version 7 keeps those benefits and restores most of the locality, at the price of revealing when the row was created. ## As a secret token RFC 9562 says implementations SHOULD NOT assume UUIDs are hard to guess and that they MUST NOT be used as **security capabilities**, meaning identifiers whose mere possession grants access. A password-reset link or a session token is exactly that. The factories differ in how badly they fail: - `nameUUIDFromBytes` can be computed by anyone who knows the input, so it is never a secret. - `ofEpochMillis` reveals its creation time and has 74 random bits. - `randomUUID` draws from a strong generator, so guessing its 122 bits is not a realistic attack, and the RFC prefers version 4 if a UUID must be used in a security operation. A dedicated token is still the better design: its length is your choice, it has no fixed bits, and it does not look like an identifier that is safe to log. For a token, fill 32 bytes with `SecureRandom.nextBytes` and encode them with `Base64.getUrlEncoder().withoutPadding()`. ## Reading a UUID back - `timestamp()`, `clockSequence()` and `node()` work only on version 1 and throw `UnsupportedOperationException` otherwise, including on version 7. - `compareTo` compares the two halves with `Long.compare`, which is signed, so its order can differ from comparing raw bytes.
- Does Java's UUID.ofEpochMillis produce strictly increasing values?Only across different milliseconds, and only if you pass rising timestamps: the Javadoc leaves monotonicity to the caller. Apart from the version and variant bits, the other 74 bits are random, so two values made in the same millisecond come out in random order. For strict order, pass a timestamp that always rises, or build a counter into the bits yourself with `new UUID(long, long)`.
- How do you get a version 7 UUID on Java 25 LTS?Java 25 has no factory for it, since `UUID.ofEpochMillis` arrived in Java 26. `new UUID(mostSigBits, leastSigBits)` accepts any bits, so you build one yourself: the millisecond timestamp in the top 48 bits, `7` in the version field, the variant bits `10`, and `SecureRandom` bits for the rest. `version()` then returns 7.
- Why doesn't UUID.timestamp() return the time of a version 7 UUID in Java?`timestamp()`, `clockSequence()` and `node()` are defined only for version 1 and throw `UnsupportedOperationException` for every other version, including 7. Version 7 stores Unix milliseconds in its top 48 bits, so read them with `uuid.getMostSignificantBits() >>> 16`.
- Does Java's UUID.compareTo always sort the same way as a database comparing raw bytes?No. `compareTo` uses `Long.compare` on the two halves, which is signed, so a value whose top bit is set sorts before one whose top bit is clear, the reverse of an unsigned byte comparison. Random version 4 values can therefore sort differently. Version 7 values with present-day timestamps have a clear top bit, so between different milliseconds both orders follow time.
- randomUUID uses java.util.Random, so its output is predictable.
- All 128 bits of a randomUUID value are random.
- nameUUIDFromBytes mixes in randomness, so two calls with equal bytes differ.
- A UUID is the right primary key for every table because it is globally unique.
- UUID.timestamp() returns the creation time of any UUID, including version 7.
- A version 7 UUID reveals nothing about when its row was created.
- java.util.UUID
- Java 1.5
- UUID.ofEpochMillis, the version 7 factory
- Java 26
Assumes Java 27; UUID.ofEpochMillis arrived in Java 26, so Java 25 LTS has no version 7 factory.
context
- UUID (Java SE 27 & JDK 27)docs.oracle.com
- RFC 9562: Universally Unique IDentifiers (UUIDs)www.rfc-editor.org
- UUID.java at jdk-27-gagithub.com