Last active
September 8, 2018 15:43
-
-
Save gubed/a08553a0da1f5e1e51b4 to your computer and use it in GitHub Desktop.
A secure alternative to System.Random
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Public Class SecureRandom : Inherits Security.Cryptography.RandomNumberGenerator | |
Private ReadOnly rng As New Security.Cryptography.RNGCryptoServiceProvider() | |
Private Function GetRandomBytes() As Byte() | |
Dim data As Byte() = New Byte(4 - 1) {} | |
rng.GetBytes(data) | |
Return data | |
End Function | |
Public Function [Next]() As Integer | |
Return BitConverter.ToInt32(GetRandomBytes(), 0) And (Integer.MaxValue - 1) | |
End Function | |
Public Function [String](len As Integer, Optional charset As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") As SecureString | |
Dim sb As New SecureString() | |
Dim letter As String = String.Empty | |
While True | |
While String.IsNullOrEmpty(letter) OrElse Not charset.Contains(letter) | |
If sb.Length = len Then | |
sb.MakeReadOnly() | |
Return sb | |
End If | |
Dim oneByte As Byte() = New Byte(4-1) {} | |
rng.GetBytes(oneByte) | |
Dim c As Char = CChar(oneByte(0)) | |
If Char.IsDigit(c) OrElse Char.IsLetter(c) Then | |
letter = c.ToString() | |
End If | |
End While | |
sb.AppendChar(letter.ToCharArray()(0)) | |
letter = String.Empty | |
End While | |
sb.MakeReadOnly() | |
Return sb | |
End Function | |
Public Function [Next](maxValue As Integer) As Integer | |
Return [Next](0, maxValue) | |
End Function | |
Public Function [Next](minValue As Integer, maxValue As Integer) As Integer | |
If minValue > maxValue Then Throw New ArgumentOutOfRangeException() | |
Return CInt(Math.Floor((minValue + (CDbl(maxValue) - minValue) * NextDouble()))) | |
End Function | |
Public Function NextDouble() As Double | |
Return BitConverter.ToUInt32(GetRandomBytes(), 0) / (UInteger.MaxValue + 1.0) | |
End Function | |
Public Function NextDouble(minimum As Double, maximum As Double) As Double | |
Return NextDouble() * (maximum - minimum) + minimum | |
End Function | |
Public Overrides Sub GetBytes(data As Byte()) | |
rng.GetBytes(data) | |
End Sub | |
Public Overrides Sub GetNonZeroBytes(data As Byte()) | |
rng.GetNonZeroBytes(data) | |
End Sub | |
End Class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment