Home / ASP.NET Wiki / .NET Framework Essentials / Generate a Random Password

Generate a Random Password

 Rate It (0)

This is simple and effective method for generation of a random password

Public Function GeneratePassword(ByVal PwdLength As Integer) As String
    Dim _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
    Dim rndNum As New Random()
    Dim chars(PwdLength - 1) As Char
    Dim strLength As Integer = _allowedChars.Length
    For i As Integer = 0 To PwdLength - 1
        chars(i) = _allowedChars.Chars(CInt(Fix((_allowedChars.Length) * rndNum.NextDouble())))
    Next i
    Return New String(chars)
End Function

 

Nimish Garg
Software Developer
Indiamart Intermesh Limited, Noida

To Get Free ASP.NEt & Oracle Code Snippets
Follow: http://nimishgarg.blogspot.com

Revision number 1, Saturday, March 27, 2010 12:59:01 PM by nimish_soft
This is not the most up to date version of this article. The most recent version can be found here.

Comments

A C# version I wrote for anyone interested: string pwdChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"; char[] pwdElements = pwdChars.ToCharArray(); Random random = new Random(); StringBuilder builder = new StringBuilder(); //Generate password in loop for(int i = 0; i passwordLength; i++) { int randomChar = random.Next(0, pwdElements.Length); builder.Append(pwdElements[randomChar]); } return builder.ToString();

Can we not use Membership.GeneratePassword method to generate rendom password? It's built method available in Membership class.

you can generate the password by using dotnet's membership class.the difference is here we can get at least one NonalphanumericNumbers here.....

Yeah to be honest Membership.GeneratePassword() does seem like a better alternative, but I'll bare this function in mind when working in old .NET Framework environments!

curtwrc is right !

Thanks! maybe you can add the C# version here!

if you want correctly using this function in a cycle then you should have static instanse of variable rndNum

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. francissvk (1)
  2. deepeshsp (1)