Home > Blockchain >  Password generator. Display 8 non-duplicate passwords in ListBox
Password generator. Display 8 non-duplicate passwords in ListBox

Time:09-21

good day. There is a code for generating passwords.

  Dim i_keys As Integer
        Dim numKeys As Integer = 8

        Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
        Dim stringChars = New Char(7) {}
        Dim random = New Random()

        For i As Integer = 0 To stringChars.Length - 1
            stringChars(i) = chars.Chars(random.Next(chars.Length))
        Next i

        Dim finalString = New String(stringChars)

        For i_keys = 1 To numKeys
            ListBox1.Items.Add(finalString)
        Next

But as a result, I get the following:

0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf
0EbrQ4Pf

Tell me how you can make it so that you get 10 random (not repeated) passwords at the output.

CodePudding user response:

You need the last loop to encompass a bit more code.

Dim i_keys As Integer
Dim numKeys As Integer = 8

Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
Dim random = New Random()

For i_keys = 1 To numKeys
    Dim stringChars = New Char(7) {}
    For i As Integer = 0 To stringChars.Length - 1
        stringChars(i) = chars.Chars(random.Next(chars.Length))
    Next i

    Dim finalString = New String(stringChars)

    ListBox1.Items.Add(finalString)
Next

CodePudding user response:

Your password generator is outside of the loop. This code is not very elegant but here you go (including a check if the password is unique):

       Dim i_keys As Integer
        Dim numKeys As Integer = 10

        Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
        Dim stringChars = New Char(7) {}
        Dim random = New Random()
           

        Dim finalString = New String(stringChars)

        For i_keys = 1 To numKeys

             For i As Integer = 0 To stringChars.Length - 1
                  stringChars(i) = chars.Chars(random.Next(chars.Length))
              Next i
            finalString = New String(stringChars)
            If  ListBox1.Items.Contains(finalString) then
                   i_keys  = i_keys  -1
            else
               ListBox1.Items.Add(finalString)
            End if
          
        Next

Please try using datatypes like List(Of String) instead.

  • Related