Native UUID Generation

Here is a function that will work across platforms:

Protected Function GenerateUUID() As String
  // From http://www.cryptosys.net/pki/uuid-rfc4122.html
  //
  // Generate 16 random bytes (=128 bits)
  // Adjust certain bits according to RFC 4122 section 4.4 as follows:
  // set the four most significant bits of the 7th byte to 0100'B, so the high nibble is '4'
  // set the two most significant bits of the 9th byte to 10'B, so the high nibble will be one of '8', '9', 'A', or 'B'.
  // Convert the adjusted bytes to 32 hexadecimal digits
  // Add four hyphen '-' characters to obtain blocks of 8, 4, 4, 4 and 12 hex digits
  // Output the resulting 36-character string "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  
  dim randomBytes as MemoryBlock = Crypto.GenerateRandomBytes(16)
  randomBytes.LittleEndian = false
  
  //
  // Adjust seventh byte
  //
  dim value as byte = randomBytes.Byte(6)
  value = value and &b00001111 // Turn off the first four bits
  value = value or &b01000000 // Turn on the second bit
  randomBytes.Byte(6) = value
  
  //
  // Adjust ninth byte
  //
  value = randomBytes.Byte(8)
  value = value and &b00111111 // Turn off the first two bits
  value = value or &b10000000 // Turn on the first bit
  randomBytes.Byte(8) = value
  
  
  dim result as string = EncodeHex(randomBytes)
  result = result.LeftB(8) + "-" + result.MidB(9, 4) + "-" + result.MidB(13, 4) + "-" + result.MidB(17, 4) + _
  "-" + result.RightB(12)
  
  return result
  
End Function

And a validator:

Protected Function ValidateUUID(s As String) As Boolean
  // Validates a RFC-4122 random UUID like the ones generated by
  // GenerateUUID
  
  static rxValidator as RegEx
  if rxValidator is nil then
    rxValidator = new RegEx
    rxValidator.SearchPattern = "(?mi-Us)\\A[[:xdigit:]]{8}-[[:xdigit:]]{4}-4[[:xdigit:]]{3}-[89AB][[:xdigit:]]{3}-[[:xdigit:]]{12}\\z"
  end if
  
  return rxValidator.Search(s) IsA RegExMatch
End Function