C# random alphanumeric strings ?

  • Thread starter Thread starter bitshift
  • Start date Start date
Anyone got an example ?

1) Hard-code a string with all the characters you want to include
2) Use a single instance of Random (with appropriate locking if you're
going to use it from many threads)
3) Create a StringBuilder of the right length
4) In a for loop, append the next random character by using
Random.Next, passing in the string's length, and using string's
indexer
5) Call ToString on the StringBuilder

Jon
 
bitshift said:
Anyone got an example ?

Also,

///
using System;
using System.Text;

....

public string GetRandomString (Random rnd, int length)
{
string charPool
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder rs = new StringBuilder();

while (length-- > 0)
rs.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);

return rs.ToString();
}
///

Watch out for wrapping on the charPool line! Note, the method takes an
instance of the Random class, which you can instantiate with new Random().

The reason it doesn't do this itself is that (I think) the Random class uses
a timer as it's entropy source, and if you try to generate a large sequence
of random numbers quickly, the seeds will match and you'll get matching
random sequences.

So the way I tested this was:

///
public static void Main ()
{
int i = 50;
Random rnd = new Random();
while (i-- > 0)
Console.WriteLine(GetRandomString(rnd, 10));
}
///
 
Jon said:
1) Hard-code a string with all the characters you want to include
2) Use a single instance of Random (with appropriate locking if you're
going to use it from many threads)
3) Create a StringBuilder of the right length
4) In a for loop, append the next random character by using
Random.Next, passing in the string's length, and using string's
indexer
5) Call ToString on the StringBuilder

Jon

Hi Jon,

Great minds think alike.
 
Here is some code that will generate a cryptograhically random unique string
of any length you want:

using System.Security.Cryptography;
using System.Text;

namespace UniqueKey
{
public class KeyGenerator
{
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b%(chars.Length - 1)]);
}
return result.ToString();
}
}
}

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder(BETA): http://www.blogmetafinder.com
 
Anyone got an example ?
Two questions:

- do you want characters in the string to repeat or not?
- is the output going to be used for cryptographic/security purposes?

rossum
 
bitshift said:
Anyone got an example ?

private static Random rng = new Random();
public static string newPassword(int l)
{
char[] valid = { 'A', 'B', 'C', '2', '3', '4' };
StringBuilder sb = new StringBuilder("");
for(int i = 0; i < l; i++)
{
sb.Append(valid[rng.Next(valid.Length)]);
}
return sb.ToString();
}

Arne
 
I suppose you could do it this way if you prefer:
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();

Actually, there are 64 characters in the string. Good catch.

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder(BETA): http://www.blogmetafinder.com



Arne Vajhøj said:
Peter said:
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();

Why the new char[62] ?

Arne
 
I suppose you could do it this way if you prefer:
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();

I think the point is, why _wouldn't_ you prefer to do it that way?

Creating an empty 62-element array doesn't seem useful. That char[]
instance just gets thrown away when the subsequent assignment is made. So
why do it at all?

I could be missing something, but it seems to me that that line of code is
just superfluous.

Pete
 
Peter said:
Arne Vajhøj said:
Peter said:
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
Why the new char[62] ?
whoops, my bad. There are indeed 62 characters in the string.

It does not matter. The only difference is whether 62 or
64 chars get GC'ed.

Arne
 
Back
Top