You can use UUID this way to get always the same UUID for your input String:

 String aString="JUST_A_TEST_STRING";
 String result = UUID.nameUUIDFromBytes(aString.getBytes()).toString();
Answer from uraimo on Stack Overflow
Top answer
1 of 4
252

You can use UUID this way to get always the same UUID for your input String:

 String aString="JUST_A_TEST_STRING";
 String result = UUID.nameUUIDFromBytes(aString.getBytes()).toString();
2 of 4
21

UUID.nameUUIDFromBytes() only generates MD5 UUIDs. However, SHA1 is preferred over MD5, if backward compatibility is not an issue.

The utility class below generates MD5 UUIDs and SHA-1 UUIDs. Feel free to use and share.

package com.example;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Generates UUIDv3 (MD5) and UUIDv5 (SHA1).
 *
 * It is fully compliant with RFC-4122.
 */
public class HashUuid {

    private static final int V3 = 3; // MD5
    private static final int V5 = 5; // SHA-1

    private static final String HASH_V3 = "MD5";
    private static final String HASH_V5 = "SHA-1";

    public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
    public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
    public static final UUID NAMESPACE_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
    public static final UUID NAMESPACE_X500 = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);

    public static UUID v3(String name) {
        return generate(V3, HASH_V3, null, name);
    }

    public static UUID v5(String name) {
        return generate(V5, HASH_V5, null, name);
    }

    public static UUID v3(UUID namespace, String name) {
        return generate(V3, HASH_V3, namespace, name);
    }

    public static UUID v5(UUID namespace, String name) {
        return generate(V5, HASH_V5, namespace, name);
    }

    private static UUID generate(int version, String algorithm, UUID namespace, String name) {

        MessageDigest hasher = hasher(algorithm);

        if (namespace != null) {
            ByteBuffer ns = ByteBuffer.allocate(16);
            ns.putLong(namespace.getMostSignificantBits());
            ns.putLong(namespace.getLeastSignificantBits());
            hasher.update(ns.array());
        }

        hasher.update(name.getBytes(StandardCharsets.UTF_8));
        ByteBuffer hash = ByteBuffer.wrap(hasher.digest());

        final long msb = (hash.getLong() & 0xffffffffffff0fffL) | (version & 0x0f) << 12;
        final long lsb = (hash.getLong() & 0x3fffffffffffffffL) | 0x8000000000000000L;

        return new UUID(msb, lsb);
    }

    private static MessageDigest hasher(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(String.format("%s not supported.", algorithm));
        }
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        UUID namespace = UUID.randomUUID();
        String name = "JUST_A_TEST_STRING";

        System.out.println(String.format("UUID.nameUUIDFromBytes():     '%s'", UUID.nameUUIDFromBytes(name.getBytes())));
        System.out.println();
        System.out.println(String.format("HashUuid.v3(name):            '%s'", HashUuid.v3(name)));
        System.out.println(String.format("HashUuid.v5(name):            '%s'", HashUuid.v5(name)));
        System.out.println(String.format("HashUuid.v3(namespace, name): '%s'", HashUuid.v3(namespace, name)));
        System.out.println(String.format("HashUuid.v5(namespace, name): '%s'", HashUuid.v5(namespace, name)));
    }
}

This is the output:

UUID.nameUUIDFromBytes():     '9e120341-627f-32be-8393-58b5d655b751'

HashUuid.v3(name):            '9e120341-627f-32be-8393-58b5d655b751'
HashUuid.v5(name):            'e4586bed-032a-5ae6-9883-331cd94c4ffa'
HashUuid.v3(namespace, name): 'f0043437-723b-308f-a6c0-74ec36ddf9c2'
HashUuid.v5(namespace, name): '18a45fd8-8fab-5647-aad7-1d3264932180'

Alternatively, you can also use uuid-creator. See this example:

// Create a UUIDv5 (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);
🌐
Java2s
java2s.com › example › java-utility-method › uuid-create › generateuuid-string-seed-abace.html
Java UUID Create generateUuid(String seed)
public static UUID generateUuid(String seed) //package com.java2s; //License from project: Apache License import java.io.UnsupportedEncodingException; import java.util.UUID; public class Main { /**/*w w w . j a v a 2 s . c o m*/ * Generates a GUID using a seed.
Discussions

linux - Repeated set of UUIDs from java's UUID.randomUUID() - Stack Overflow
I'm not sure this is a security question, but a java internals question. ... What if whatever internal storage used to keep this UUID seed thingy is a file that is managed via Chef / Puppet / part of a VM snapshot? I think it's legitimate to ask how this allegedly unique seed is stored and ... More on stackoverflow.com
🌐 stackoverflow.com
design - Is it possible to build a system to generate UUIDs where every UUID is guaranteed unique? - Software Engineering Stack Exchange
Is it possible to design a distributed system to generate unique ids where there is a requirement that every generated id is guaranteed to be unique with no possibility of collision? I didn't think... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
same uuid based on seed string in js - javascript
I found this answer Is there any way to generate the same UUID based on the seed string in JDK or some library? but this is the java way. I need to the same, but in javascript, i can use any npm m... More on stackoverflow.com
🌐 stackoverflow.com
random - Java UUID.randomUUID() or SecureRandom for id segment on URL? - Information Security Stack Exchange
Looking at the source for Java's random UUID generation, you can see they actually utilize the SecureRandom class to generate the raw bytes. So, the 'quality' of your randomness isn't going to change. The fact that you have 6 more bits does, technically, make it more difficult to brute force a duplicate. Wikipedia's article on UUID ... More on security.stackexchange.com
🌐 security.stackexchange.com
October 24, 2016
🌐
Reddit
reddit.com › r/learnprogramming › uuid v4 and seeds
r/learnprogramming on Reddit: UUID v4 and Seeds
August 6, 2023 -

I've been learning about UUIDs and have a few questions about version 4 implementation.

I understand that the likelihood of generating the same UUID is incredibly small, but is that likelihood jeopardized at all by the random number generator and seed used? Maybe the likelihood of using the same seed is incredibly small too, so how does one go about choosing a good seed? I'm thinking about this from the perspective of someone implementing their own UUID generator. I assume that the libraries available have good implementations.

I guess the question I'm really asking is this, when implementing a version 4 UUID generator how does one avoid seed related issues creating duplicate UUIDs?

Thanks!

🌐
Tabnine
tabnine.com › home page › code › java › java.util.uuid
java.util.UUID.nameUUIDFromBytes java code examples | Tabnine
private String generateUuid(final String propposedId, final String destinationGroupId, final String seed) { long msb = UUID.nameUUIDFromBytes((propposedId + destinationGroupId).getBytes(StandardCharsets.UTF_8)).getMostSignificantBits(); UUID uuid; if (StringUtils.isBlank(seed)) { long lsb = randomGenerator.nextLong(); // since msb is extracted from type-one UUID, the type-one semantics will be preserved uuid = new UUID(msb, lsb); } else { UUID seedId = UUID.nameUUIDFromBytes((propposedId + destinationGroupId + seed).getBytes(StandardCharsets.UTF_8)); uuid = new UUID(msb, seedId.getLeastSignificantBits()); } LOG.debug("Generating UUID {} from currentId={}, seed={}", uuid, propposedId, seed); return uuid.toString(); } ... /** * Sets the identifier of the builder with a UUID generated from the specified seed string.
🌐
Apache JIRA
issues.apache.org › jira › browse › JCR-1206
[JCR-1206] UUID generation: SecureRandom should be used by default - ASF Jira
Currently, the UUID generation used the regular java.util.Random implementation to generate random UUIDs. The seed value of Random is initialized using System.currentTimeMillis(); for Windows, the resolution is about 15 milliseconds. That means two computer that start creating UUIDs with Jackrabbit within the same 15 millisecond interval will generate the same UUIDs.
🌐
UUID Generator
uuidgenerator.net
Online UUID Generator Tool
Quickly and easily generate individual or bulk sets of universally unique identifiers (UUIDs).
Top answer
1 of 1
21

From JDK 1.6 source, indeed, UUID.randomUUID() feeds on a java.util.SecureRandom instance. If you got a repeated sequence of UUID, then either you got very lucky (or very unlucky, depending on your point of view), or someone played with VM snapshots, or there is something fishy in your Java configuration.

When taking a VM snapshot, you record the complete live state of the machine, processes and RAM included. If there was a live process with an already instantiated SecureRandom instance, restoring the snapshot will bring back that state, so the sequence of random values output by that SecureRandom will be the same each time a restore occurs, until the SecureRandom reseeds itself from /dev/urandom (/dev/urandom continuously gathers "random" physical events, but these won't impact the SecureRandom state until the next reseeding).

The Java configuration may impact SecureRandom, in that SecureRandom is NOT a PRNG, but a shell around an instance of SecureRandomSpi provided by a duly registered cryptographic provider. Sun's JDK comes with a default implementation that normally feeds on the system's resources (/dev/urandom on Linux). However, this can be configured; lookup the java.security.egd system property, and also the securerandom.source property in the java.security file. The default provider may also be replaced altogether with an alternate implementation that does things differently (and possibly very poorly). See this answer for some details. Verifying what random source is indeed used can be a bit complex, but you could try launching your process with strace, which will show system calls, hence whether /dev/random or /dev/urandom is opened at some point.

If your Java configuration is fine, and there was no game with VM snapshots, and you are sure that you indeed got the same sequence of UUID as previously, then you really really should have bought a Powerball ticket instead (but I do not honestly believe in this scenario).

Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › guide to uuid in java
Guide to UUID in Java | Baeldung
May 15, 2025 - However, Java provides an implementation only for v3 and v4. Alternatively, we can use the constructor to generate the other types. UUID version 1 uses the current timestamp and the MAC address of the device generating the UUID. In particular, the timestamp is measured in units of 100 nanoseconds from October 15, 1582. Still, if privacy is a concern, we can use a random 48-bit number instead of the MAC address. With this in mind, let’s generate the least significant and most significant 64 bits as long values:
🌐
Apache JIRA
issues.apache.org › jira › browse › SPARK-23599
[SPARK-23599] The UUID() expression is too non-deterministic - ASF Jira
It uses a single secure random for UUID generation. This uses a single JVM wide lock, and this can lead to lock contention and other performance problems. We should move to something that is deterministic between retries. This can be done by using seeded PRNGs for which we set the seed during ...
🌐
TutorialsPoint
tutorialspoint.com › java › util › uuid_randomuuid.htm
Java UUID randomUUID() Method
The method call returns a randomly generated UUID. ... The following example shows usage of Java UUID randomUUID() method to get a type 3 (name based) UUID based on the specified byte array. We've created a UUID object using randomUUID() method.
🌐
Marc Nuri
marcnuri.com › uuid
UUID / GUID Online key generator
The generated keys are type 4 pseudo randomly generated UUIDs. The Java implementation uses java.security.SecureRandom that uses an unpredictable value as the seed in order to comply with RFC 1750 making its output strong and lowering the chances of collisions.
Top answer
1 of 11
32

there is a finite number of ids which can fit into some structure

Correct. If you have n bits in your structure, after you have generated 2^n IDs, the next one must be a collision; this is the pigeonhole principle.

However, assuming you are dealing with an actual physical system rather than a pure thought experiment, there are "only" 10^80 = 2^265 electrons in the universe so if your data structure is bigger than 265 bits or so then, given a perfect algorithm, you'll never be able to generate all the IDs.

2 of 11
21

You want version 1 UUIDs. They don't collide but they leak the generating computer's MAC address and require a monotonic clock.

From RFC4122 we have this format

8 bytes time-low
2 bytes time-mid
2 bytes time-high & version (high nybble is a 1)
2 bytes clock-seq-high & reserved (high two bits are 1 and 0)
2 bytes clock-seq-low
6 bytes MAC address

Clock-sequence is actually the subsecond portion of the clock now.

The thing about the two byte fiedls is they are not two one byte fields. If you mess the code up, you get different results on little endian and big endian machines and you have a chance of collision again. The string form looks like this no matter what your endian is:

????????-????-1???-[89AB]???-?[02468ACE]??????????

The thing about this is when it works, it works. If you don't have MAC address collisions (the general rule is if you get colliding MAC addresses, RMA both cards) and if you actually have a monotonic clock, this works 100% of the time.

There's a work around for not having a monotonic clock. That is, do it the old way. Serialize all UUID generations and use clock-seq as a counter that increments with each generation.

The thing about this is you will have bad generation and most likely collisions if your PC battery dies on any node that generates.

It's been pointed out in comments that VMs don't really get globally unique MAC addresses, and it has also been pointed out that the solution to this is to hand out the node IDs yourself. When you do this you are supposed to set the broadcast bit (the one marked [02468ACE] so that it would match [13579BDF] instead).

If you can't tolerate leaking the MAC addresses and can't issue node IDs, you're stuck with lesser means. V4 UUIDs are really good for all terrestrial use under modern hardware assumptions (has thermal diode or other hardware RNG). V5 UUIDs can do the job under specific circumstances (they're a hash of something else; the main problem is they're subject to adversarial attack).

Top answer
1 of 2
9

In terms of the raw amount of random bits, yes.

Looking at the source for Java's random UUID generation, you can see they actually utilize the SecureRandom class to generate the raw bytes. So, the 'quality' of your randomness isn't going to change.

The fact that you have 6 more bits does, technically, make it more difficult to brute force a duplicate. Wikipedia's article on UUID has a good description of the math behind it. To quote it:

[A]fter generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%

If these links are going to expire in, say, 24 hours, this is a very small thing to worry about, and that's only with 122 bits.

Now, is more bits going to make it harder for an attacker to brute force a collision? Sure! Is it worth it? Maybe... but maybe not. Only you can really decide what's right for your use case.

When you get to the point where brute forcing a collision would, on average, take longer than the time for the estimated heat death of the universe, it might be a little overboard. That's getting to the territory of needing to worry more about hackers compromising the security of your storage more than brute forcing (and, honestly, even with UUIDs, you're going to have that problem). Ultimately, the difficulty of brute forcing doesn't matter if they can find another way in. If you're really worried, storage is cheap - store 256 bit strings that you generate with a SecureRandom and call it good, but make sure you have proper security around everything else, or it's useless.

2 of 2
9

Well, in principle, UUIDs and cryptographic RNGs promise two different things:

  1. UUIDs promise low probability of duplicates;
  2. Cryptographic RNGs promise unpredictability to a malicious adversary.

If #2 is a concern, I'd make sure to use a cryptographic RNG. For example, if you're concerned that a malicious attacker who can request a lot of UUIDs in a short timespan might learn enough information to predict those given out to other users' requests.

As it happens, Java's UUID.randomUUID() method does use a cryptographic RNG, so it should be safe in that regard. But the risk then is that developers who later look at your code may not understand that your intent includes secure cryptographic random choice, and not just uniqueness. For example, somebody might rewrite that particular module using some other language or UUID library that does not use a cryptographic RNG, and expose you to prediction-based attacks that you meant to exclude. So if cryptographic security really was an important factor I'd try to write the code in a way that makes that obvious, by using SecureRandom explicitly. (Security-critical code needs to be very clear!)

If all I cared for was uniqueness instead of security then I'd go ahead and use UUID.randomUUID().

🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › UUID.html
UUID (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... A class that represents an immutable universally unique identifier (UUID).
🌐
JUCE
forum.juce.com › general juce discussion
UUID from specific Random seed value? - General JUCE discussion - JUCE
January 9, 2026 - the juce::Uuid constructor implementation is as follows: Uuid::Uuid() { Random r; for (size_t i = 0; i < sizeof (uuid); ++i) uuid[i] = (uint8) (r.nextInt (256)); // To make it RFC 4122 compliant, …
🌐
coderolls
coderolls.com › uuid-in-java
Your Guide To UUID In Java - Coderolls
December 19, 2020 - ... Mostly Randomly Generated UUID i.e. UUID Version 4 is used. UUID Version 4 uses random numbers as a source. It uses an unpredictable value as the seed to generate random numbers to reduce the chance of collisions ... Mostly variant 2 is used. ... UUID Class belongs to the java.util package.
🌐
GitHub
github.com › oracle › graal › issues › 2265
Windows - native-image - UUID.randomUUID() returns always the same uuid · Issue #2265 · oracle/graal
March 17, 2020 - On Windows, native-image based binary always returns the same uuid when calling UUID.randomUUID().toString(). On macOS and Linux with native-image based binary, the returned value is always different. Using GraalVM Version 20.0.0 CE JDK11 on all the systems ... import java.util.UUID; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); System.out.println(UUID.randomUUID().toString()); } }
Author   rsvoboda