Click here to Skip to main content
11,711,750 members (78,553 online)
Click here to Skip to main content

Generating Unique Keys in .Net

, 17 Jun 2006 252K 6.9K 106
Rate this:
Please Sign up or sign in to vote.
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.

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

<BR>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(chars[__b % (chars.Length - )>); }
 <span class="code-keyword">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

Share

About the Author

Altaf Al-Amin
United Arab Emirates United Arab Emirates
Altaf Al-Amin Najvani
Project Manager
Commercial Bank Of Dubai


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

Certifications:
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)

You may also be interested in...

Comments and Discussions

 
Questionasdasd Pin
Member 1180103729-Jun-15 9:21
memberMember 1180103729-Jun-15 9:21 
General[My vote of 2] You are comparing different things Pin
_groo_8-Oct-12 1:10
member_groo_8-Oct-12 1:10 
GeneralMy vote of 5 Pin
GedeonGP19-Jul-12 18:46
memberGedeonGP19-Jul-12 18:46 
GeneralMy vote of 1 Pin
netizenk18-Jul-12 9:31
membernetizenk18-Jul-12 9:31 
GeneralRe: My vote of 1 Pin
wout de zeeuw23-Sep-12 5:30
memberwout de zeeuw23-Sep-12 5:30 
SuggestionVB.Net version Pin
Member 822886530-Jun-12 1:49
memberMember 822886530-Jun-12 1:49 
Questionon using GUIDS as primary keys ... f.y.i. Pin
gerry lowry13-Jun-12 6:58
membergerry lowry13-Jun-12 6:58 
QuestionDuplicates, less frequently, do get created using the RNG technique too! Pin
gerry lowry13-Jun-12 6:52
membergerry lowry13-Jun-12 6:52 
GeneralMy vote of 5 Pin
shoebass21-Feb-12 21:27
membershoebass21-Feb-12 21:27 
GeneralProblem with the code Pin
love_chopra127-Apr-11 2:01
memberlove_chopra127-Apr-11 2:01 
GeneralKeeping things simple Pin
Harout Saryan23-Mar-11 15:54
memberHarout Saryan23-Mar-11 15:54 
GeneralMy vote of 5 Pin
Nariman Marvi11-Aug-10 0:43
memberNariman Marvi11-Aug-10 0:43 
GeneralMy execution times are different [modified] Pin
schuetz17-Aug-09 21:45
memberschuetz17-Aug-09 21:45 
GeneralMy vote of 2 Pin
Antonio Herrero Lopes19-May-09 18:49
memberAntonio Herrero Lopes19-May-09 18:49 
GeneralThanks alot Pin
ammarcs15-Mar-09 12:30
memberammarcs15-Mar-09 12:30 
GeneralRe: Thanks alot Pin
Altaf Al-Amin15-Mar-09 18:52
memberAltaf Al-Amin15-Mar-09 18:52 
Generalthanks for youre helpful guide Pin
sooarty18-Nov-08 1:51
membersooarty18-Nov-08 1:51 
GeneralUniqueKey CS to VB Pin
jkirkerx17-Sep-08 8:59
memberjkirkerx17-Sep-08 8:59 
GeneralRe: UniqueKey CS to VB Pin
800XL23-Nov-09 4:37
member800XL23-Nov-09 4:37 
GeneralRe: UniqueKey CS to VB Pin
jkirkerx23-Nov-09 7:25
memberjkirkerx23-Nov-09 7:25 
GeneralRe: UniqueKey CS to VB Pin
jkirkerx23-Nov-09 7:31
memberjkirkerx23-Nov-09 7:31 
GeneralThank you! Pin
LarsHB25-Jun-08 21:09
memberLarsHB25-Jun-08 21:09 
GeneralShort and instructive. Pin
BugMeNot ACCOUNT10-Apr-08 7:10
memberBugMeNot ACCOUNT10-Apr-08 7:10 
GeneralNice Article Pin
shouvik969-Apr-08 5:09
membershouvik969-Apr-08 5:09 
GeneralRe: Nice Article Pin
sai_sss18-Jul-10 22:57
membersai_sss18-Jul-10 22:57 
QuestionCan u help me???? Pin
shouvik968-Apr-08 1:01
membershouvik968-Apr-08 1:01 
AnswerRe: Can u help me???? Pin
BugMeNot ACCOUNT10-Apr-08 7:06
memberBugMeNot ACCOUNT10-Apr-08 7:06 
GeneralWorks great, here are some more stats on the RNGCryptoServiceProvider and Character Masking Method Pin
acormier31-Mar-08 5:15
memberacormier31-Mar-08 5:15 
GeneralRe: Works great, here are some more stats on the RNGCryptoServiceProvider and Character Masking Method Pin
A-MEN4-Apr-08 0:03
memberA-MEN4-Apr-08 0:03 
Questionhow to generate unique key Pin
biswa4710-Aug-07 1:49
memberbiswa4710-Aug-07 1:49 
GeneralSha1 or Md5 Pin
afterburn18-Jun-06 16:16
memberafterburn18-Jun-06 16:16 
GeneralRe: Sha1 or Md5 Pin
mitchell5019-Jun-06 6:21
membermitchell5019-Jun-06 6:21 
GeneralRe: Sha1 or Md5 Pin
eggsovereasy22-Jun-06 8:22
membereggsovereasy22-Jun-06 8:22 
GeneralRe: Sha1 or Md5 Pin
mitchell5022-Jun-06 14:50
membermitchell5022-Jun-06 14:50 
GeneralPurpose Pin
mitchell5016-Jun-06 10:36
membermitchell5016-Jun-06 10:36 
GeneralRe: Purpose Pin
Altaf Al-Amin17-Jun-06 19:26
memberAltaf Al-Amin17-Jun-06 19:26 
GeneralRe: Purpose Pin
kasajian21-Jun-06 4:11
memberkasajian21-Jun-06 4:11 
GeneralRe: Purpose Pin
mitchell5021-Jun-06 5:49
membermitchell5021-Jun-06 5:49 
GeneralRe: Purpose Pin
dave.dolan24-Sep-06 16:14
memberdave.dolan24-Sep-06 16:14 
GeneralRe: Purpose Pin
mitchell5025-Sep-06 6:42
membermitchell5025-Sep-06 6:42 
GeneralAn easier way Pin
djlove14-Jun-06 2:03
memberdjlove14-Jun-06 2:03 
GeneralRe: An easier way Pin
Altaf Al-Amin17-Jun-06 19:28
memberAltaf Al-Amin17-Jun-06 19:28 
GeneralRe: An easier way Pin
Steve Hansen18-Jun-06 5:45
memberSteve Hansen18-Jun-06 5:45 
GeneralRe: An easier way Pin
Scoby92-Aug-07 9:43
memberScoby92-Aug-07 9:43 
Generalfrequency distibution of generated letters Pin
System.Object13-Jun-06 2:22
memberSystem.Object13-Jun-06 2:22 
GeneralRe: frequency distibution of generated letters Pin
Altaf Al-Amin13-Jun-06 4:40
memberAltaf Al-Amin13-Jun-06 4:40 
GeneralRe: frequency distibution of generated letters Pin
System.Object13-Jun-06 7:48
memberSystem.Object13-Jun-06 7:48 
GeneralShortened GUID Pin
Paul Charles13-Jun-06 1:19
memberPaul Charles13-Jun-06 1:19 
GeneralBirthday Paradox Pin
ttobler12-Jun-06 6:25
memberttobler12-Jun-06 6:25 
GeneralGetHashcode Pin
Roger J11-Jun-06 23:33
memberRoger J11-Jun-06 23:33 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150819.1 | Last Updated 18 Jun 2006
Article Copyright 2006 by Altaf Al-Amin
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid