How to generate a GUID/UUID?

What is the best way to generate a GUID/UUID from Apex code (such as a trigger)? Preferably in the following format:

nnnnnnnn-nnnn-nnnn-nnnnnnnnnnnnnnnnn

Example:

13219ec0-3a81-44c5-a300-de14b7d0235f

Answer

The answer provided by Paul Sasik above works, but is not a secure way of generating a UUID because of it’s use of Math.Random(), which is not a cryptographically secure pseudo-random number generator.

One of two things should be done, either use Crypto.getRandomInteger() to generate the random integer or use the code below as a drop in replacement for the whole UUID generation routine:

Blob b = Crypto.GenerateAESKey(128);
String h = EncodingUtil.ConvertTohex(b);
String guid = h.SubString(0,8)+ '-' + h.SubString(8,12) + '-' + h.SubString(12,16) + '-' + h.SubString(16,20) + '-' + h.substring(20);

Sources:

Attribution
Source : Link , Question Author : Paul Sasik , Answer Author : rev

Leave a Comment