• We just launched and are currently in beta. Join us as we build and grow the community.

How to generate a Random number using RNGCryptoServiceProvid

hooman_z70

Boss Slayer
Divine
H Rep
0
0
0
Rep
0
H Vouches
0
0
0
Vouches
0
Posts
49
Likes
21
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
Submitted by
planetsourcecode

on
Thu, 06/11/2009 - 00:52

We can easily generate a unique Random number by using the inbuilt class "RNGCryptoServiceProvider".For doing this simply add class namespace to the header of the code-behind.

using System.Security.Cryptography;

write a simple function "GetUniqueKey"

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 - 1)]);
}
return result.ToString();
}

and call this function in form load or any event like button.

string strTest = GetUniqueKey();
strTest = "BL/2009/" + strTest;
Response.Write(strTest);

One highlight thing is that we can add any format to this Unique ID in this case "BL/2009"

source codes:

1). Design

%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Untitled Page

2). Code Behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strTest = GetUniqueKey();
strTest = "BCL/2009/" + strTest;
Response.Write(strTest);
}
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 - 1)]);
}
return result.ToString();
}

}

About the author:

Planet Source Code is a place for all developer providing free source codes, articles, complete projects,complete application in PHP, C/C++, Javascript, Visual Basic, Cobol, Pascal, ASP/VBScript, AJAX, SQL, Perl, Python, Ruby, Mobile Development

 

437,153

314,794

314,803

Top