Generating cryptographically secure random strings

Per the official MSDN entry on System.Random ( System.Random generates Pseudo-random numbers that are "chosen with equal probability from a finite set of numbers". This can cause repeated patterns and pre-determinable "random" strings. Because of this generating random strings from the System.Random class is absolutely NOT cryptographically secure.
.NET offers the System.Security.Cryptography.RNGCryptoServiceProvider class to generate effectively random strings, Generation is a little more complicated because a range cannot be specified. The following function(s)
    Public Function GetSecureRandomString(ByVal iLength As Integer) As String
        Dim result As New StringBuilder
        Dim number(0) As Byte
        Using gen As New RNGCryptoServiceProvider()
            While result.Length < iLength
                If IsNumInRange(number(0), 32, 126) Then
                End If
            End While
        End Using

        Return result.ToString
    End Function

    Private Function IsNumInRange(ByVal number As Integer, ByVal rngStart As Integer, ByVal rngStop As Integer) As Boolean
        If number >= rngStart AndALso number < rngStop Then
            Return True
        End If
        Return False
    End Function

Add Feedback