How to generate random password in VB.NET

3 Answers

0 votes
Imports System
Imports System.Text

Public Class Program
    Public Shared Function GenerateRandomPassword(ByVal length As Integer) As String
        Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&"
        Dim sb As StringBuilder = New StringBuilder()
        Dim rnd As Random = New Random()

        For i As Integer = 0 To length - 1
            Dim index As Integer = rnd.[Next](chars.Length)
            sb.Append(chars(index))
        Next

        Return sb.ToString()
    End Function

    Public Shared Sub Main()
        Dim length As Integer = 7

        Dim password As String = GenerateRandomPassword(length)

        Console.WriteLine(password)
    End Sub
End Class


         
         
         
 
' run:
'
' dE#R$xx
'




 



answered Aug 17, 2023 by avibootz
0 votes
Imports System
Imports System.Linq
 
Public Class Program
    Public Shared Function GenerateRandomPassword(ByVal length As Integer) As String
        Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&"
        Dim rnd As Random = New Random()
         
        Return New String(Enumerable.Repeat(chars, length).Select(Function(s) s(rnd.Next(s.Length))).ToArray())
    End Function
 
    Public Shared Sub Main()
        Dim length As Integer = 7
     
        Dim password As String = GenerateRandomPassword(length)
     
        Console.WriteLine(password)
    End Sub
End Class
 
 
 
          
          
          
  
' run:
'
' &6Y&M!9
'

 



answered Aug 17, 2023 by avibootz
edited Aug 17, 2023 by avibootz
0 votes
Imports System
Imports System.Security.Cryptography

Public Class Program
    Public Shared Function GenerateRandomPassword(ByVal length As Integer) As String
        Dim password As Byte() = New Byte(length - 1) {}
		
        Dim rngCrypt As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
        rngCrypt.GetBytes(password)
        
		Return Convert.ToBase64String(password)
    End Function

    Public Shared Sub Main()
        Dim length As Integer = 7
		
        Dim password As String = GenerateRandomPassword(length)
		
        Console.WriteLine(password)
    End Sub
End Class



         
         
         
 
' run:
'
' pXGZfFSC5g==
'

 



answered Aug 17, 2023 by avibootz
...