5,276,801 members and growing! (16,980 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Generating Unique Keys in .Net

By Altaf Al-Amin

I need to create some unique IDs. GUIDs are great as they give Globally Unique identifier but they are big. I mean if you want to issue unique number in your application which you want to give as Booking Number or any reference number then GUIDs is obviously not a solution.
C++, C#, VB, Windows, .NET, Visual Studio, ASP.NET, Arch, Dev, QA

Posted: 9 Jun 2006
Updated: 17 Jun 2006
Views: 44,697
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
31 votes for this Article.
Popularity: 5.46 Rating: 3.66 out of 5
3 votes, 10.3%
1
3 votes, 10.3%
2
4 votes, 13.8%
3
7 votes, 24.1%
4
12 votes, 41.4%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

I have few applications where I need to create some unique IDs. GUIDs are great as they give Globally Unique identifier but they are big. I mean if you want to issue unique number in your application which you want to give as Booking Number or any reference number then GUIDs is obviously not a solution. Therefore, I need some simple Id which is unique too. For example when I send a request to my Credit Card Processor there's an ID that correlates my invoice with the transaction at the provider. A GUID isn't what I'd want here.

But one relatively simple solution is to create sequential ID which will be of appropriate size as well as it will guarantee uniqueness. Very Good and Simple solution!!! Isn’t it !! My answer would be NO !! Because it is security threat for your website. In case of Web Application where you can Retrieve your Order or Booking Details by just giving Order Reference number, you can easily BruteForce Sequential Reference numbers to retrieve records.

In this article I will discuss some of my research and techniques.

Using DateTime and HashCode:

Using DateTime for generating unique keys is very common practice. I have remixed this approach by inducing HashCode in it also. Like

DateTime.Now.ToString().GetHashCode().ToString("x"); 

It will give you some key like 496bffe0. At the first glance it seems to be satisfied Unique key as its using current time and hashing to generate key but GetHashCode() doesn’t procduce unique code everytime. Althought Microsoft is using Double Hashing algorithms with N Number of collision resolving double hash function but during my experimentation I found lot of collisions.

Using GUIDs and HashCode:

So then I tried


Guid.NewGuid().ToString().GetHashCode().ToString("x");

It gives key something like 649cf2e3

Somehow I don't think that this string representation at least is unique… 38 characters represented as 8? Ok 32 bits, but still it's 8 digits and characters limited to hex values and yes my doubt got right as I wrote program which generated 100,000 keys and checked it for collisions and found several keys duplicated.

Using RNGCryptoServiceProvider and Character Masking

The .net Framwork 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 I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length. Below is code sample:

  private string GetUniqueKey()
  {
  int maxSize  = 8 ;
  int minSize = 5 ;
  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(chars1)>); }
   return result.ToString();
  }

Analysis:

For lab testing purposes, I created 10,00,000 unique keys by using above three procedures and found the following results :

Generation Method

Time Taken

Number of Generated Keys

Number of Duplicate Keys

All Fixed Length Keys

 

Using DateTime and HashCode

01.56 sec 

10,00,000

500131

No

 

Using GUIDs and HashCode

04.45 sec

10,00,000

113

No

 

Using RNGCryptoServiceProvider and Character Masking

 

00.40 sec

10,00,000

0 (Wow!!)

Yes

 


The above analysis shows that RNGCrypto with Character Masking is best method to generate Unique keys.

Note: The above research is for study purpose only. Yes there can be another methods which are better than the ones mentioned above.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Altaf Al-Amin


Altaf Najvani
Microsoft Certified Application Developer
Microsoft Certified Solution Developer
Microsoft Certified Technology Specialist (SQL Server 2005)
Microsoft Certified Technology Specialist(Web Applications)

He has done his BS in Computer Science and currently pursing Masters In Project Management. He is currently working as e-Banking Consultant for Commercial Bank Of Dubai.You can reach Altaf at altaf.alamin@gmail.com.
Location: United Arab Emirates United Arab Emirates

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 36 (Total in Forum: 36) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralThank you!memberLarsHB22:09 25 Jun '08  
GeneralShort and instructive.memberBugMeNot ACCOUNT8:10 10 Apr '08  
GeneralNice Articlemembershouvik966:09 9 Apr '08  
GeneralCan u help me????membershouvik962:01 8 Apr '08  
GeneralRe: Can u help me????memberBugMeNot ACCOUNT8:06 10 Apr '08  
GeneralWorks great, here are some more stats on the RNGCryptoServiceProvider and Character Masking Methodmemberacormier6:15 31 Mar '08  
GeneralRe: Works great, here are some more stats on the RNGCryptoServiceProvider and Character Masking MethodmemberA-MEN1:03 4 Apr '08  
Generalhow to generate unique keymemberbiswa472:49 10 Aug '07  
GeneralSha1 or Md5memberafterburn17:16 18 Jun '06  
GeneralRe: Sha1 or Md5membermitchell507:21 19 Jun '06  
GeneralRe: Sha1 or Md5membereggsovereasy9:22 22 Jun '06  
GeneralRe: Sha1 or Md5membermitchell5015:50 22 Jun '06  
GeneralPurposemembermitchell5011:36 16 Jun '06  
GeneralRe: PurposememberAltaf Al-Amin20:26 17 Jun '06  
GeneralRe: Purposememberkasajian5:11 21 Jun '06  
GeneralRe: Purposemembermitchell506:49 21 Jun '06  
GeneralRe: Purposememberdave.dolan17:14 24 Sep '06  
GeneralRe: Purposemembermitchell507:42 25 Sep '06  
GeneralAn easier waymemberdjlove3:03 14 Jun '06  
GeneralRe: An easier waymemberAltaf Al-Amin20:28 17 Jun '06  
GeneralRe: An easier waymemberSteve Hansen6:45 18 Jun '06  
GeneralRe: An easier waymemberScoby910:43 2 Aug '07  
Generalfrequency distibution of generated lettersmemberSystem.Object3:22 13 Jun '06  
GeneralRe: frequency distibution of generated lettersmemberAltaf Al-Amin5:40 13 Jun '06  
GeneralRe: frequency distibution of generated lettersmemberSystem.Object8:48 13 Jun '06