source: unsplash.com

How Rails generates UUIDs by extending the digest library

An overview of the UUID specification and the Digest::UUID module

Tech - RubyCademy
RubyCademy
Published in
2 min readOct 13, 2019

--

What’s a UUID?

UUID stands for Universally Unique IDentifier — also known as GUID (Globally Unique IDentifier).

It’s a sequence of bits used to ensure the identification of a unique resource.

A UUID is 128 bits long and can guarantee uniqueness across space and time.

There are currently 5 versions of UUIDs.

They are known as versions 1, 2, 3, 4 and 5.

Each version implements a set of variations more or less complex.

For example, the UUID v1 specification is based on date-time and MAC address.

On the other hand, the UUID v4 specification defines a set of 122 bits randomly generated.

As you noticed, each version defines its own way to generate the UUID.

Feel free to browse the RFC 4122 for further information about each version.

Now that we’re more familiar with the notion of UUID, let’s see how Ruby on Rails extends the digest library to implement versions 3, 4, and 5 of the UUID specification.

The Digest::UUID module

This module provides a set of helper methods to generate UUIDs for versions 3, 4, and 5 – as defined in the RFC 4122 specification

In the above example, we use the uuid_v3 , uuid_v4 and uuid_v5 methods to generate UUIDs.

These 3 methods respectively return a UUID v3, UUID v4, and UUID v5.

The uuid_v4 method simply uses the return value of SecureRandom.uuid.

Indeed, as defined in the UUID v4 specification, 122 bits are randomly generated.

So, this specification is already implemented by the SecureRandom.uuid method.

Now, the UUID v3 and UUID v5 specifications are almost similar.

They are composed of a mix of a namespace and a name that is encrypted using the MD5 algorithm (UUID v3) or the SHA-1 algorithm (UUID v5).

All this logic is encapsulated in the uuid_from_hash method that is internally called by both the uuid_v3 and uuid_v5 methods.

The uuid_from_hash method takes 3 arguments:

  • the encryption algorithm (MD5 or SHA-1)
  • the namespace
  • the name

So when we call

Internally the uuid_v3 method calls the uuid_from_hash method with the following arguments

As defined in the specification, UUID version 3 uses the MD5 algorithm to generate the hash.

For uuid_v5

As defined in the specification, UUID version 5 uses the SHA-1 algorithm to generate the hash.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--