Click here to Skip to main content
15,166,980 members
Articles / Web Development / ASP.NET
Posted 9 Jun 2006


118 bookmarked

Generating Unique Keys in .Net

Rate me:
Please Sign up or sign in to vote.
3.74/5 (64 votes)
17 Jun 20063 min read
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.


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


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


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];
StringBuilder result = new StringBuilder(size) ;
foreach(byte b in data )
{ result.Append(chars^__b % (chars.Length - )>); }
 <span class="code-keyword">return result.ToString();


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

Generation Method<o:p>

Time Taken<o:p>

Number of Generated Keys<o:p>

Number of Duplicate Keys<o:p>

All Fixed Length Keys<o:p>


Using DateTime and HashCode<o:p>

01.56 sec  <o:p>





Using GUIDs and HashCode<o:p>

04.45 sec<o:p>





Using RNGCryptoServiceProvider and Character Masking<o:p>


00.40 sec<o:p>


0 (Wow!!)<o:p>



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.



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
United Arab Emirates United Arab Emirates
Altaf Al-Amin Najvani
Project Manager
Commercial Bank Of Dubai

BS - Computer Science
Masters In Project Management
Masters In Business Administration

CISA - Certified Information Systems Auditor
ITIL (Foundation)
Microsoft Certified Technology Specialist (SQL Server 2005)
Microsoft Certified Technology Specialist (Web Applications)
Microsoft Certified Application Developer (.NET)
Microsoft Certified Solution Developer (.NET)

Comments and Discussions

QuestionRampant Plagiarism Pin
Rick Shaw2-Oct-17 7:30
MemberRick Shaw2-Oct-17 7:30 
Questioninteresting, but too much code. Pin
Ryan C. Price13-Dec-15 15:16
MemberRyan C. Price13-Dec-15 15:16 
Questionasdasd Pin
ronnyaul29-Jun-15 10:21
Memberronnyaul29-Jun-15 10:21 
General[My vote of 2] You are comparing different things Pin
_groo_8-Oct-12 2:10
Member_groo_8-Oct-12 2:10 
GeneralMy vote of 5 Pin
GedeonGP19-Jul-12 19:46
MemberGedeonGP19-Jul-12 19:46 
GeneralMy vote of 1 Pin
netizenk18-Jul-12 10:31
professionalnetizenk18-Jul-12 10:31 
GeneralRe: My vote of 1 Pin
wout de zeeuw23-Sep-12 6:30
Memberwout de zeeuw23-Sep-12 6:30 
SuggestionVB.Net version Pin
Member 822886530-Jun-12 2:49
MemberMember 822886530-Jun-12 2:49 
Questionon using GUIDS as primary keys ... f.y.i. Pin
gerry lowry13-Jun-12 7:58
Membergerry lowry13-Jun-12 7:58 
QuestionDuplicates, less frequently, do get created using the RNG technique too! Pin
gerry lowry13-Jun-12 7:52
Membergerry lowry13-Jun-12 7:52 
GeneralMy vote of 5 Pin
shoebass21-Feb-12 22:27
Membershoebass21-Feb-12 22:27 
GeneralProblem with the code Pin
love_chopra127-Apr-11 3:01
Memberlove_chopra127-Apr-11 3:01 
GeneralKeeping things simple Pin
Harout Saryan23-Mar-11 16:54
MemberHarout Saryan23-Mar-11 16:54 
GeneralMy vote of 5 Pin
Nariman Marvi11-Aug-10 1:43
MemberNariman Marvi11-Aug-10 1:43 
GeneralMy execution times are different [modified] Pin
roni schuetz17-Aug-09 22:45
Memberroni schuetz17-Aug-09 22:45 
GeneralMy vote of 2 Pin
AntonioLopes19-May-09 19:49
MemberAntonioLopes19-May-09 19:49 
GeneralThanks alot Pin
ammarcs15-Mar-09 13:30
Memberammarcs15-Mar-09 13:30 
GeneralRe: Thanks alot Pin
Altaf Al-Amin15-Mar-09 19:52
MemberAltaf Al-Amin15-Mar-09 19:52 
Generalthanks for youre helpful guide Pin
sooarty18-Nov-08 2:51
Membersooarty18-Nov-08 2:51 
GeneralUniqueKey CS to VB Pin
jkirkerx17-Sep-08 9:59
professionaljkirkerx17-Sep-08 9:59 
GeneralRe: UniqueKey CS to VB Pin
800XL23-Nov-09 5:37
Member800XL23-Nov-09 5:37 
GeneralRe: UniqueKey CS to VB Pin
jkirkerx23-Nov-09 8:25
professionaljkirkerx23-Nov-09 8:25 
GeneralRe: UniqueKey CS to VB Pin
jkirkerx23-Nov-09 8:31
professionaljkirkerx23-Nov-09 8:31 
QuestionNumbers Only? Pin
migmb12-Aug-08 6:46
Membermigmb12-Aug-08 6:46 
AnswerRe: Numbers Only? Pin
Altaf Al-Amin12-Aug-08 7:47
MemberAltaf Al-Amin12-Aug-08 7:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.