Cryptographically Random Unique String

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!

4 Comments

  1. Posted August 26, 2007 at 2:46 pm | Permalink

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

  2. Posted August 26, 2007 at 10:43 pm | Permalink

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

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

  3. Posted November 11, 2007 at 7:20 am | Permalink

    Thank you for posting this – helped a lot!

  4. Nikola
    Posted December 5, 2007 at 11:14 am | Permalink

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