Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUID, 30 character random string

Tags:

guid

I need to generate a unique string that is 30 characters in length. At first, I was going to generate a GUID and just remove the first two characters.

Guid.NewGuid().ToString("N").Substring(2);

Will removing the two first characters have a significant effect on the "uniqueness"? Is it something that I should be worried about?

Is there a better way of generating a random 30 character string that will be guaranteed to be unique?

like image 583
harmony Avatar asked Jul 15 '10 21:07

harmony


2 Answers

Removing two hexadecimal characters or equivalently 8 bits from a GUID will make it less unique but 120 bits still make a quite good unique value. If you don't want to generate millions of ids every second it should be safe to remove some bits from the timestamp and uniquifier without risking a collision. See for example the Wikipedia for the structure of GUIDs.

An alternative solution would be to encode the GUID in Base64 or something like that if you are not constraint to hexadecimal characters only. 128 bits encoded in Base64 yield a string of length 24. Then you can even add another 6 random characters to pad the string to 30 characters making it even more unique.

like image 95
Daniel Brückner Avatar answered Sep 17 '22 14:09

Daniel Brückner


Truncating a GUID loses the uniqueness. To understand why you should understand how a GUID is created. It consists of a few parts:

  • 60 bits of timestamp
  • 48 bits of computer identifier
  • 14 bits of uniquifier
  • 6 bits are fixed

By discarding the first two characters you are discarding the 8 most significant bits of the timestamp part. This article explains it well and the dangers of truncating GUIDs. It also explains how you could use the same technique used in GUIDs to create unique identifiers that are not globally unique but will be unique for more constrained circumstances.

like image 41
Mark Byers Avatar answered Sep 18 '22 14:09

Mark Byers