UUID.randomUUID() vs SecureRandom

User3518958 picture User3518958 · Sep 30, 2016 · Viewed 20k times · Source

I am trying to understand the advantages of using UUID.randomUUID() over SecureRandom generator as the former uses securerandom internally.

Answer

uoyilmaz picture uoyilmaz · Sep 30, 2016

Well, the source code shows UUID.randomUUID uses SecureRandom.

public static UUID  [More ...] randomUUID() {
    SecureRandom ng = numberGenerator;
    if (ng == null) {
        numberGenerator = ng = new SecureRandom();
    }
    byte[] randomBytes = new byte[16];
    ng.nextBytes(randomBytes);
    randomBytes[6]  &= 0x0f;  /* clear version        */
    randomBytes[6]  |= 0x40;  /* set to version 4     */
    randomBytes[8]  &= 0x3f;  /* clear variant        */
    randomBytes[8]  |= 0x80;  /* set to IETF variant  */
    return new UUID(randomBytes);
}

As you can see, you can use either, but in a secure UUID you have 6 non-random bits, which can be considered a disadvantage if you are picky.