Generating random password

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi

How can I generate a random password of 8 characters (digits and letters) in
vb?

Thanks

Regards
 
Dim objRandomNumberGenerator As New System.Random
Dim strPassword As String = ""
Dim intX As Integer

For intX = 1 To 8

'Randomly decide whether or not the next character will be a letter
If objRandomNumberGenerator.Next(0, 2) = 0 Then

'Letter
strPassword &= Chr(objRandomNumberGenerator.Next(97, 123))

Else

'Digit
strPassword &= Chr(objRandomNumberGenerator.Next(48, 58))

End If

Next
 
Hi John, almost the same :)

Public Function GeneratePassword(ByVal len As Integer) As String
Dim str As String =
"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
Dim N As Integer = str.Length
Dim rnd As New Random((Now.Hour * 3600 + Now.Minute * 60 +
Now.Second) * 1000 + Now.Millisecond)
Dim sb As New StringBuilder

For l As Integer = 1 To len
sb.Append(str.Substring(rnd.Next(0, N), 1))
Next
Return sb.ToString
End Function

generates 'random' passwords every 1 millisecond. Using inside class
scope make random number generator Shared to avoid this
limitation. :))
Kind regards
Serge
http://www.sergejusz.com
 
John said:
Hi

How can I generate a random password of 8 characters (digits and letters) in
vb?

Thanks

Regards

Make a string that contains the characters that you want to use. Here
you can remove the characters that easily can be misinterpreted, like 1,
l, I, o , O, 0. Pick characters by random from the string.

Example:

Dim chars as String = "2345ABCD"
Dim password as String = ""
Dim r as New Random()
Dim i as Integer
For i = 1 to 8
password += chars.Substring(r.Next(chars.Length), 1)
Next
 
Back
Top