Cryptographically Random Unique String

15 08 2007

Looking for a way to create a Random Password Generator, I came across the following code written by Peter Bromberg (I thought to post it here in case it saves someone some time). This code will generate a cryptographically random unique string of any length you want.

Ah! BTW, I’ve made a very small modification to the original code

using System.Security.Cryptography;
using System.Text;
 
namespace UniqueKey
{
    public class KeyGenerator
    {
 
        public string GetUniqueKey()
        {
 
            int maxSize = 8;
            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();
        }
    }
}

Thanks Peter for the code!


Actions

Informations

4 responses to “Cryptographically Random Unique String”

26 08 2007
keshuvko (14:46:39) :

Did the modification work?
I tried the both but none fruit in my case. :(
Help!

26 08 2007
Juan Wong (22:43:04) :

Of course both samples work! That’s why I posted it here.

You’re writing a class with the above code, right?

11 11 2007
Jobst von Heintze - Web 2.0 Designer (07:20:02) :

Thank you for posting this – helped a lot!

5 12 2007
Nikola (11:14:36) :

exsacly what i was looking for thank you for sharing with me




LiveSTRONG