Click here to Skip to main content
15,886,963 members
Articles / Programming Languages / Visual Basic
Article

Generate a Random String Key in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.56/5 (22 votes)
27 Jul 20052 min read 186.7K   3.7K   31   11
A slightly more intelligent random string generator.

Sample Image

Introduction

I had to create a piece of code that will give me a set of randomly generated keys. Each key had to consist of letters and numbers, and the letters could be either (randomly) lowercase or uppercase.

Looking at some sample code on the web, I could not find what I needed. All the examples I found either generated numbers only, or letters only. I also wanted this random key to be based on a certain rule that made it "not straightforward" random, so, I came up with this little piece of code.

Using the code

The way it works is as follows:

You feed it with a string of letters: KeyLetters, a string of numbers: KeyNumbers, and how many characters you want the random key to be: Keychars. We then call Generate() which goes and generates a random number through the Randomize() statement and the Rnd() function.

Multiply Rnd() by 111 -could be any number we choose which is sufficient enough to bring the value above zero. If the resulting number is an even number, then our random character will be a letter. If we get an odd number, then our random character will be a number. To generate a random character, we generate a random index for one of the character arrays (depending on what our random character will be). Once we have an index which is >= o, we use it to get the value in the corresponding index in the character array.

If we are generating a number, then that is our random character. If we are generating a letter, then we need to determine whether we want it uppercase or lowercase. For that purpose we generate another random number by multiplying the value of Rnd() by 99 – could be any other number too – and then determine whether the result is even or odd. This time, we capitalize the letter if we get an odd number, otherwise we leave it as it is.

And so on, … the loop keeps "looping" while using, and we use a StringBuilder to construct our resulting string , until we've generated the desired number of characters for our Random Key. We convert the StringBuilder to String and return it with the function.

Note: XML comments in the source code were generated using "VBXC - VB.NET XML Commentor beta 3". I highly recommend it.

Module1.vb

VB
Module Module1
    Sub Main()
        Dim KeyGen As RandomKeyGenerator
        Dim NumKeys As Integer
        Dim i_Keys As Integer
        Dim RandomKey As String

        ''' MODIFY THIS TO GET MORE KEYS    - LAITH - 27/07/2005 22:48:30 -
        NumKeys = 20

        KeyGen = New RandomKeyGenerator
        KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
        KeyGen.KeyNumbers = "0123456789"
        KeyGen.KeyChars = 12
        For i_Keys = 1 To NumKeys
            RandomKey = KeyGen.Generate()
            Console.WriteLine(RandomKey)
        Next
        Console.WriteLine("Press any key to exit...")
        Console.Read()
    End Sub
End Module

RandomKeyGenerator.vb

VB
Option Strict On
Imports System.Text
''' <date>27072005</date><time>070339</time>
''' <type>class</type>
''' <summary>
''' REQUIRES PROPERTIES: KeyLetters, KeyNumbers, MaxChars
''' </summary>
Public Class RandomKeyGenerator
    Dim Key_Letters As String
    Dim Key_Numbers As String
    Dim Key_Chars As Integer
    Dim LettersArray As Char()
    Dim NumbersArray As Char()

    ''' <date>27072005</date><time>071924</time>
    ''' <type>property</type>
    ''' <summary>
    ''' WRITE ONLY PROPERTY. HAS TO BE SET BEFORE CALLING GENERATE()
    ''' </summary>
    Protected Friend WriteOnly Property KeyLetters() As String
        Set(ByVal Value As String)
            Key_Letters = Value
        End Set
    End Property

    ''' <date>27072005</date><time>071924</time>
    ''' <type>property</type>
    ''' <summary>
    ''' WRITE ONLY PROPERTY. HAS TO BE SET BEFORE CALLING GENERATE()
    ''' </summary>
    Protected Friend WriteOnly Property KeyNumbers() As String
        Set(ByVal Value As String)
            Key_Numbers = Value
        End Set
    End Property

    ''' <date>27072005</date><time>071924</time>
    ''' <type>property</type>
    ''' <summary>
    ''' WRITE ONLY PROPERTY. HAS TO BE SET BEFORE CALLING GENERATE()
    ''' </summary>
    Protected Friend WriteOnly Property KeyChars() As Integer
        Set(ByVal Value As Integer)
            Key_Chars = Value
        End Set
    End Property

    ''' <date>27072005</date><time>072344</time>
    ''' <type>function</type>
    ''' <summary>
    ''' GENERATES A RANDOM STRING OF LETTERS AND NUMBERS.
    ''' LETTERS CAN BE RANDOMLY CAPITAL OR SMALL.
    ''' </summary>
    ''' <returns type="String">RETURNS THE
    '''         RANDOMLY GENERATED KEY</returns>
    Function Generate() As String
        Dim i_key As Integer
        Dim Random1 As Single
        Dim arrIndex As Int16
        Dim sb As New StringBuilder
        Dim RandomLetter As String

        ''' CONVERT LettersArray & NumbersArray TO CHARACTR ARRAYS
        LettersArray = Key_Letters.ToCharArray
        NumbersArray = Key_Numbers.ToCharArray

        For i_key = 1 To Key_Chars
            ''' START THE CLOCK    - LAITH - 27/07/2005 18:01:18 -
            Randomize()
            Random1 = Rnd()
            arrIndex = -1
            ''' IF THE VALUE IS AN EVEN NUMBER WE GENERATE A LETTER,
            ''' OTHERWISE WE GENERATE A NUMBER  
            '''          - LAITH - 27/07/2005 18:02:55 -
            ''' THE NUMBER '111' WAS RANDOMLY CHOSEN. ANY NUMBER
            ''' WILL DO, WE JUST NEED TO BRING THE VALUE
            ''' ABOVE '0'     - LAITH - 27/07/2005 18:40:48 -
            If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
                ''' GENERATE A RANDOM INDEX IN THE LETTERS
                ''' CHARACTER ARRAY   - LAITH - 27/07/2005 18:47:44 -
                Do While arrIndex < 0
                    arrIndex = _
                     Convert.ToInt16(LettersArray.GetUpperBound(0) _
                     * Random1)
                Loop
                RandomLetter = LettersArray(arrIndex)
                ''' CREATE ANOTHER RANDOM NUMBER. IF IT IS ODD,
                ''' WE CAPITALIZE THE LETTER
                '''      - LAITH - 27/07/2005 18:55:59 -
                If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
                    RandomLetter = LettersArray(arrIndex).ToString
                    RandomLetter = RandomLetter.ToUpper
                End If
                sb.Append(RandomLetter)
            Else
                ''' GENERATE A RANDOM INDEX IN THE NUMBERS
                ''' CHARACTER ARRAY   - LAITH - 27/07/2005 18:47:44 -
                Do While arrIndex < 0
                    arrIndex = _
                      Convert.ToInt16(NumbersArray.GetUpperBound(0) _
                      * Random1)
                Loop
                sb.Append(NumbersArray(arrIndex))
            End If
        Next
        Return sb.ToString
    End Function
End Class

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionLicense Pin
superjohn_200625-Feb-15 4:29
superjohn_200625-Feb-15 4:29 
Questioncode in vb.net(windows application) Pin
Member 927728020-Jul-12 0:34
Member 927728020-Jul-12 0:34 
QuestionThanx Pin
afridibest24-Apr-12 0:18
afridibest24-Apr-12 0:18 
Generalgood job Pin
beyhano31-Mar-08 12:13
beyhano31-Mar-08 12:13 
GeneralGood but Pin
smiling4ever10-Aug-05 3:15
smiling4ever10-Aug-05 3:15 
GeneralRe: Good but Pin
Baiju Nagori12-May-06 9:22
Baiju Nagori12-May-06 9:22 
QuestionRe: Good but Pin
mhovidz13-Apr-07 7:51
mhovidz13-Apr-07 7:51 
AnswerRe: Good but Pin
smiling4ever13-Apr-07 8:15
smiling4ever13-Apr-07 8:15 
AnswerRe: Good but Pin
Laith M. Zraikat5-Aug-08 0:35
Laith M. Zraikat5-Aug-08 0:35 
GeneralRe: Good but Pin
Shane Story6-Feb-09 4:31
Shane Story6-Feb-09 4:31 
GeneralRe: Good but Pin
Anthony Granger10-Feb-09 14:27
Anthony Granger10-Feb-09 14:27 
[code]' zRanP, written by NightCrawler03X
' Copyright (C) 2009 NightCrawler03X, All Rights Reserved
' In regards to this software, permission to use, copy, modify, reproduce, redistribute (under the definitions of international copyright law),
' is hereby granted, but the above copyright notice must remain, and the following disclaimer applies:
'' ''THIS SOFTWARE IS PROVIDED ''AS IS'', AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
'' ''THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
'' ''THE COPYRIGHT HOLDER OF THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
'' ''BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERUPTION)
'' ''HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'' ''(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
'' ''OF SUCH DAMAGE.

'' Should you have any questions, direct them to nightcrawler03x@gmail.com
'' You may also find me under the following aliases at the following forums (just sign up and send me a private message):
'' zerohero (http://forums.xkcd.com),
'' NightCrawler03X (http://www.ubuntuforums.org, http://www.programmingforums.org, http://www.daniweb.com)

Option Strict On
Option Explicit On
Module Module1

Private amountPasswords As Integer = 0
Private maxLength As Integer = 0
Private minLength As Integer = 0

Private Function generatePassword(ByRef minLength As Integer, ByRef maxLength As Integer) As String
Dim s As String = "" : Dim passwordLength As Integer = 0 : generatePassword = ""
Do : Randomize() : passwordLength = Convert.ToInt32(minLength + Int(Rnd() * (maxLength - minLength)))
Loop Until passwordLength >= minLength
For i As Integer = 1 To passwordLength Step 1 : Randomize()
Do : s = Chr(Convert.ToInt32(33 + Int(Rnd() * 94)))
Loop Until Not s = Chr(34) : generatePassword += s : Next
End Function

Private Sub inputMaxLength()
Do : Try : System.Console.Write("Maximum length: ")
maxLength = Convert.ToInt32(Console.ReadLine())
If Not maxLength < minLength Then Return Else System.Console.WriteLine("Cannot be below minimum length")
Catch ex As Exception : System.Console.WriteLine("GIGO") : End Try : Loop
End Sub

Private Sub inputMinLength()
Do : Try : System.Console.Write("Minimum length: ")
minLength = Convert.ToInt32(Console.ReadLine())
If Not minLength < 1 Then Return Else System.Console.WriteLine("Must be 1 or greater")
Catch ex As Exception : System.Console.WriteLine("GIGO") : End Try : Loop
End Sub

Private Sub inputAmount()
Do : Try : System.Console.Write("Amount of passwords: ")
amountPasswords = Convert.ToInt32(Console.ReadLine())
If Not amountPasswords <= 0 Then Return Else System.Console.WriteLine("GIGO")
Catch ex As Exception : System.Console.WriteLine("GIGO") : End Try : Loop
End Sub

Private Sub finalResults()
System.Console.WriteLine("")
For i As Integer = 1 To amountPasswords Step 1
System.Console.WriteLine(generatePassword(minLength, maxLength))
System.Console.WriteLine() : Next
System.Console.WriteLine("Make sure to change your password regularly.")
System.Console.WriteLine("NEVER write it down. Write it in your head, and no-where-else.")
System.Console.WriteLine("Share your password with NO-ONE")
End Sub

Sub Main()
inputAmount() : inputMinLength() : inputMaxLength() : finalResults() _
: System.Console.Write("Press any key to quit... ") : System.Console.ReadKey()
End Sub

End Module
[/code]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.