Unique Key Generator

This morning I needed to generate a unique key for an application I am working on. The key needed to be unique within the application, but I didn’t need it to be globally unique and a GUID is just too long.

I have played in the past with various combinations of DateTime, SessionID and other application specific values to cobble together an application wide unique key but really wanted something much neater, like the unique values created by sites such as TinyUrl.com

For example: http://tinyurl.com/39gg3es

So, after a little research and playing around, I came up with this:

static string GenerateKey(int keyLength) {
    char[] maskChars = "1234567890AaBcCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".ToCharArray(); 

    RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
    byte[] cryptoBytes = new byte[keyLength];

    StringBuilder key = new StringBuilder(keyLength);
        foreach(byte b in cryptoBytes)
    key.Append(maskChars[b % 62]);
    return key.ToString();

You will need to import


and can create a unique key by using the following code:

string uniqueKey = GenerateKey(6);

specifying the length of the key you require (in this case six). This will generate a key such as: D7D2iU

Please feel free to use this code as you wish. If you do use it I would love to know where and, of course, any comments or suggestions would be appreciated.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)