Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse the Cryptography API to generate secure random numbers with Visual Basic 2005
DescriptionThis example shows how to use the Cryptography API to generate secure random numbers with Visual Basic 2005.
KeywordsCryptography, Cryptography API, random numbers, random, Visual Basic 2005
CategoriesAlgorithms
 
What does "secure random number" mean? It means that an attacker, after seeing a series of random numbers that you generate, cannot predict the next one with any success. Note that the function described here is really only secure over a range of 256 values. See the discussion at the end to see why.

The RandomInteger function creates an RNGCryptoServiceProvider object (RNG stands for Random Number Generator). It then calls the object's GetBytes method to get one random byte and scales it to fit the desired range of return values.

 
' Return a random integer between a min and max value.
Public Function RandomInteger(ByVal min As Integer, ByVal _
    max As Integer) As Integer
    Dim rand As New RNGCryptoServiceProvider()
    Dim one_byte() As Byte = {0}
    rand.GetBytes(one_byte)
    Return min + (max - min) * (one_byte(0) / 255)
End Function
 
Note that the granularity of this method is only 1/256 so if you are generating numbers over a large range, you will not get every possible value. For example, if the range is 0 to 2550, then the function will return values 0, 10, 20, and so forth. If you want finer granularity, you'll need to use more bytes.

You might also want to divide by 256 instead of 255 so the function does not return the maximum value. That would be more consistent with the way .NET's Random class works.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated