tags:

views:

1750

answers:

7

I'd like to generate random unique strings like the ones being generated by MSDN library:

http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx, for example. A string like 't9zk6eay' should be generated.

+3  A: 
  • not sure Microsoft's link are randomly generated
  • have a look to new Guid().ToString()
Fabian Vilers
You mean Guid.NewGuid().ToString() - Guid doesn't have a public constructor
ck
You're probablly right, was typing w/o verfiying. I'm sure the original poster has the point.
Fabian Vilers
+6  A: 

I don't think that they really are random, but my guess is those are some hashes.

Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:

Guid.NewGuid().ToString("n");
Lucero
A: 

Get Unique Key using GUID Hash code

public static string GetUniqueKey(int length)
{
    string guidResult = string.Empty;

    while (guidResult.Length < length)
    {
        // Get the GUID.
        guidResult += Guid.NewGuid().ToString().GetHashCode().ToString("x");
    }

    // Make sure length is valid.
    if (length <= 0 || length > guidResult.Length)
        throw new ArgumentException("Length must be between 1 and " + guidResult.Length);

    // Return the first length bytes.
    return guidResult.Substring(0, length);
}
Chris Doggett
A: 

This has been asked for various languages. Here's one question about passwords which should be applicable here as well.

If you want to use the strings for URL shortening, you'll also need a Dictionary<> or database check to see whether a generated ID has already been used.

Pontus Gagge
+10  A: 

I would caution that GUIDs are not random numbers. They should not be used as the basis to generate anything that you expect to be totally random (see http://en.wikipedia.org/wiki/Globally_Unique_Identifier):

Cryptanalysis of the WinAPI GUID generator shows that, since the sequence of V4 GUIDs is pseudo-random, given the initial state one can predict up to next 250 000 GUIDs returned by the function UuidCreate. This is why GUIDs should not be used in cryptography, e. g., as random keys.

Instead, just use the C# Random method. Something like this (code found here):

private string RandomString(int size)
{
  StringBuilder builder = new StringBuilder();
  Random random = new Random();
  char ch ;
  for(int i=0; i<size; i++)
  {
    ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
    builder.Append(ch);
  }
  return builder.ToString();
}

GUIDs are fine if you want something unique (like a unique filename or key in a database), but they are not good for something you want to be random (like a password or encryption key). So it depends on your application.

Edit. Microsoft says that Random is not that great either (http://msdn.microsoft.com/en-us/library/system.random(VS.71).aspx):

To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider.

Keltex
The C# random class is not "random" either and unsuitable for any crypto code, since it is a classic random generator starting from a specific seed number. Same seed will also return the same sequence of numbers returned; the GUID approach is already much better off here (not "random" but "unique").
Lucero
@Lucero: You're correct. Microsoft recommends, "To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider."
Keltex
Well, the question already stated that he wants (pseudo-)random unique strings, so no crypto requirements or even a need for following a specific random distribution. So GUID is probably the easiest approach.
Joey
The statement that "given the initial state one can predict up to next 250 000 GUIDs" seems like an inherently true statement for *any* PRNG... I'm sure it's also not secure, but I'm not sure there's much value in generating truly random URLs, if that's what the OP is going for. ;)
ojrac
(+1 anyway -- PRNG education is important.)
ojrac
+3  A: 

Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string:

    Guid g = Guid.NewGuid();
    string GuidString = Convert.ToBase64String(g.ToByteArray());
    GuidString = GuidString.Replace("=","");
    GuidString = GuidString.Replace("+","");

I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string:

"OZVV5TpP4U6wJthaCORZEQ"

Mark Synowiec
You should consider replacing / too.
Jason Kealey
+4  A: 

This is a duplicate question, the answer given in the other is much better:

http://stackoverflow.com/questions/54991/generating-random-passwords/55447#55447

there's always System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters)

Ward Werbrouck