0

I'm just wondering what the usual method is of generating a unique string of random upper/lowercase letters of arbitrary length?

My immediate thought would be to use a guid generator provided by the programming framework I use and then apply a well known hashing algorithm to the guid.

If this is the case, what types of hashing functions do I need to look into?

Thanks

ShaunO
  • 291
  • 1
  • 6
  • 13
  • 2
    `random != unique`! Even guids are technically not unique. It's just very very *very* unlikely that the same one will be producesd twice. And that is only due to the fact that guids are basically very large numbers (much *much* more than you can have with 5 characters) and the algorithm to create them has a pretty good distribution. If you really need to guarantee uniqueness, then you somehow need to "remember" everything you ever generated and generate again if you get something you already generated. – Corak Oct 20 '13 at 05:40
  • 1
    Or better yet, for relatively small ranges: generate *all* possibilities and then randomly select one and remove it from the list of possibilities for the next time. – Corak Oct 20 '13 at 05:41

1 Answers1

2

Creating a GUID is not a good way to get a random number, as not all data in a GUID is random.

Just use the Random class. Example:

string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int len = 5;

Random rnd = new Random();
StringBuilder b = new StringBuilder(len);
for (int i = 0; i < len; i++) {
  b.Append(chars[rnd.Next(chars.Length)]);
}
string result = b.ToString();

Note however that this does not guarantee that the code is unique. To accomplish that you have to save all previous codes and check against those for any new code. Eventhough a GUID is considered unqiue enough, a short hash generated from a GUID does not have that property.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Thank you very much, an elegant solution, definitely a case of me over thinking it. – ShaunO Oct 20 '13 at 03:54
  • `Random` is not a cryptographically secure random number generator. It's possible to derive the internal state of the generator (and therefore predict all future and previous random values) from a few output values, so it cannot be used in situations where this must not happen. The .NET API does have a cryptographically secure random generator, but I can't help with this as I'm not familiar with .NET. – ntoskrnl Oct 20 '13 at 11:00
  • @ntoskrnl: That's true, but cryptographically secure doesn't mean that it's unique either. – Guffa Oct 20 '13 at 11:26
  • @ntoskrnl A [secure implementation](http://stackoverflow.com/a/13416143/445517). But with 5 character strings the gain is a bit dubious. Obviously these won't be unique either. With such short strings one has to compare against existing codes. – CodesInChaos Oct 21 '13 at 09:47