Thursday, 30 August 2007

ASP.NET - Random Key Generator

OK, you may need to generate a secure random key to maybe place in a database, or any other reason that you have. Here's a way I generate a secure case-sensitive string:

Add the following under Inherits System.Web.UI.Page:

Const minlength = 13
Const maxlength = 15
Dim m_rand As New Random

Now add a new function, like so:

Function GenerateKey()
Dim charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Dim length As Integer
length = m_rand.Next(minlength, maxlength + 1)
Dim key As New StringBuilder(length)
Dim i
For i = 0 To length
key.Append(Mid(charset, m_rand.Next(0, Len(charset)), 1))
Return key.ToString
End Function

Now all you need to do in your code is call GenerateKey() and it will return a unique key. Bear in mind that you can change the minimum and maximum length of the key by editing the const values that we added at the start.


No comments: