Description:
In this example I will explain how to generate Unique Key using C# RNGCryptoServiceProvider class. In this example I have taken dropdownlist control to specify the length of the unique key to generate. This class is available under namespace System.Security.Cryptography.
|
Design Code:
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="GetUnique.aspx.cs" Inherits="GetUnique"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title><link
href="style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td>
<asp:DropDownList ID="ddlsize"
runat="server" AutoPostBack="true">
<asp:ListItem Text="Select
size" Value="0"></asp:ListItem>
<asp:ListItem Text="10"
Value="1"></asp:ListItem>
<asp:ListItem Text="15"
Value="2"></asp:ListItem>
<asp:ListItem Text="20"
Value="3"></asp:ListItem>
<asp:ListItem Text="25"
Value="4"></asp:ListItem>
<asp:ListItem Text="30"
Value="5"></asp:ListItem>
</asp:DropDownList></td>
<td>
<asp:Button ID="btnGetkey"
runat="server" Text="Get Unique Key" OnClick="btnGetkey_Click"
/>
</td>
</tr>
</table>
<asp:Label ID="lblkey"
runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
|
C# Code:
using System;
using System.Security.Cryptography;
using System.Text;
public partial class GetUnique : System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
}
public string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
protected void btnGetkey_Click(object sender,
EventArgs e)
{
if (ddlsize.SelectedIndex > 0)
{
lblkey.Text = GetUniqueKey(Convert.ToInt32(ddlsize.SelectedItem.ToString()));
}
else
{
lblkey.Text = "<span style=color:red>Invalid size</span>";
}
}
}
|
Result: |
Thursday, May 8, 2014
C#.Net Generate Unique key using RNGCryptoServiceProvider Class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment