Generating Unique Key in .Net using RNGCryptoServiceProvider

I need to create some unique keys. GUID is one option as they give Globally Unique identifier but they are big. If you want to issue unique number in your application which you want to give as AppKey or any reference number then GUIDs is obviously not a solution.

RNG means Random Number Generator

The .net Framework provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers.

Although we can use this class to generate unique number in some sense. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only.

So, we used this function along with some character masking to generate unique key of any length (here I take 32 character long key).

Below is code sample:

private string RNGCharacterMask()

{

int maxSize = 32;

int minSize = 32;

char[] chars = new char[62];

string a;

a = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”;

chars = a.ToCharArray();

int size = maxSize;

byte[] data = new byte[1];

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

crypto.GetNonZeroBytes(data);

size = maxSize;

data = new byte[size];

crypto.GetNonZeroBytes(data);

StringBuilder result = new StringBuilder(size);

foreach (byte b in data)

{

result.Append(chars[b % (chars.Length – 1)]);

}

return result.ToString();

}

Happy Coding… 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s