Connecting Tech Pros Worldwide Help | Site Map

Generate Random Password

sashi's Avatar
Expert
 
Join Date: Jun 2006
Location: Seremban, Malaysia
Posts: 1,630
#1   Dec 4 '06
Generate Random Password

In the course of programming you may have cause to generate a password. The following function will generate a password of randomly selected characters up to a maximum of 10 characters (this is easy to increase). The number of characters required is passed as a parameter.

Using this type of procedure as opposed to chosing your own passwords makes for better security.

Expand|Select|Wrap|Line Numbers
  1. 'Form code - frmPasswordGenerate
  2.  
  3. Private Declare Function GetTickCount Lib "kernel32" () As Long
  4.  
  5. Public Function PassGen(nLen As Integer)
  6. Dim range As Collection
  7. Dim ivalue, icount, iLen As Long
  8. Dim pass As String
  9.  
  10.     Set range = New Collection
  11.     range.Add ("0")
  12.     range.Add ("1")
  13.     range.Add ("2")
  14.     range.Add ("3")
  15.     range.Add ("4")
  16.     range.Add ("5")
  17.     range.Add ("6")
  18.     range.Add ("7")
  19.     range.Add ("8")
  20.     range.Add ("9")
  21.  
  22.     icount = 0
  23.     ivalue = 0
  24.     iLen = range.Count
  25.  
  26.     Do Until icount = nLen
  27.       Randomize
  28.       ivalue = CByte(Mid(CStr(Rnd(GetTickCount)), 3, 2))
  29.        If ivalue > 0 And ivalue <= iLen Then
  30.           icount = icount + 1
  31.           pass = pass & range(ivalue)
  32.        End If
  33.     Loop
  34.  
  35. PassGen = pass
  36. End Function
  37.  
  38. Private Sub cmdGeneratePassword_Click()
  39.     MsgBox PassGen(8)
  40. End Sub
  41.  

Last edited by RedSon; Nov 21 '07 at 07:12 PM.



Reply