Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System
- Imports System.IO
- Imports System.Security.Cryptography
- Public Class HMACSHA5126example
- Public Shared Sub Main(ByVal Fileargs() As String)
- Dim dataFile As String
- Dim signedFile As String
- 'If no file names are specified, create them.
- If Fileargs.Length < 2 Then
- dataFile = "text.txt"
- signedFile = "signedFile.enc"
- If Not File.Exists(dataFile) Then
- ' Create a file to write to.
- Using sw As StreamWriter = File.CreateText(dataFile)
- sw.WriteLine("Here is a message to sign")
- End Using
- End If
- Else
- dataFile = Fileargs(0)
- signedFile = Fileargs(1)
- End If
- Try
- ' Create a random key using a random number generator. This would be the
- ' secret key shared by sender and receiver.
- Dim secretkey() As Byte = New [Byte](63) {}
- 'RNGCryptoServiceProvider is an implementation of a random number generator.
- Using rng As New RNGCryptoServiceProvider()
- ' The array is now filled with cryptographically strong random bytes.
- rng.GetBytes(secretkey)
- ' Use the secret key to encode the message file.
- SignFile(secretkey, dataFile, signedFile)
- ' Take the encoded file and decode
- VerifyFile(secretkey, signedFile)
- End Using
- Catch e As IOException
- Console.WriteLine("Error: File not found", e)
- End Try
- End Sub 'Main
- ' Computes a keyed hash for a source file and creates a target file with the keyed hash
- ' prepended to the contents of the source file.
- Public Shared Sub SignFile(ByVal key() As Byte, ByVal sourceFile As String, ByVal destFile As String)
- ' Initialize the keyed hash object.
- Using myhmac As New HMACSHA512(key)
- Using inStream As New FileStream(sourceFile, FileMode.Open)
- Using outStream As New FileStream(destFile, FileMode.Create)
- ' Compute the hash of the input file.
- Dim hashValue As Byte() = myhmac.ComputeHash(inStream)
- ' Reset inStream to the beginning of the file.
- inStream.Position = 0
- ' Write the computed hash value to the output file.
- outStream.Write(hashValue, 0, hashValue.Length)
- ' Copy the contents of the sourceFile to the destFile.
- Dim bytesRead As Integer
- ' read 1K at a time
- Dim buffer(1023) As Byte
- Do
- ' Read from the wrapping CryptoStream.
- bytesRead = inStream.Read(buffer, 0, 1024)
- outStream.Write(buffer, 0, bytesRead)
- Loop While bytesRead > 0
- End Using
- End Using
- End Using
- Return
- End Sub 'SignFile
- ' end SignFile
- ' Compares the key in the source file with a new key created for the data portion of the file. If the keys
- ' compare the data has not been tampered with.
- Public Shared Function VerifyFile(ByVal key() As Byte, ByVal sourceFile As String) As Boolean
- Dim err As Boolean = False
- ' Initialize the keyed hash object.
- Using hmac As New HMACSHA512(key)
- ' Create an array to hold the keyed hash value read from the file.
- Dim storedHash(hmac.HashSize / 8) As Byte
- ' Create a FileStream for the source file.
- Using inStream As New FileStream(sourceFile, FileMode.Open)
- ' Read in the storedHash.
- inStream.Read(storedHash, 0, storedHash.Length - 1)
- ' Compute the hash of the remaining contents of the file.
- ' The stream is properly positioned at the beginning of the content,
- ' immediately after the stored hash value.
- Dim computedHash As Byte() = hmac.ComputeHash(inStream)
- ' compare the computed hash with the stored value
- Dim i As Integer
- For i = 0 To storedHash.Length - 2
- If computedHash(i) <> storedHash(i) Then
- err = True
- End If
- Next i
- End Using
- End Using
- If err Then
- Console.WriteLine("Hash values differ! Signed file has been tampered with!")
- Return False
- Else
- Console.WriteLine("Hash values agree -- no tampering occurred.")
- Return True
- End If
- End Function 'VerifyFile
- End Class 'HMACSHA5126example 'end VerifyFile
- 'end class
- 'The following sample uses the Cryptography class to simulate the roll of a dice.
- Imports System
- Imports System.IO
- Imports System.Text
- Imports System.Security.Cryptography
- Class RNGCSP
- Private Shared rngCsp As New RNGCryptoServiceProvider()
- ' Main method.
- Public Shared Sub Main()
- Const totalRolls As Integer = 25000
- Dim results(5) As Integer
- ' Roll the dice 25000 times and display
- ' the results to the console.
- Dim x As Integer
- For x = 0 To totalRolls
- Dim roll As Byte = RollDice(System.Convert.ToByte(results.Length))
- results((roll - 1)) += 1
- Next x
- Dim i As Integer
- While i < results.Length
- Console.WriteLine("{0}: {1} ({2:p1})", i + 1, results(i), System.Convert.ToDouble(results(i)) / System.Convert.ToDouble(totalRolls))
- i += 1
- End While
- rngCsp.Dispose()
- Console.ReadLine()
- End Sub
- ' This method simulates a roll of the dice. The input parameter is the
- ' number of sides of the dice.
- Public Shared Function RollDice(ByVal numberSides As Byte) As Byte
- If numberSides <= 0 Then
- Throw New ArgumentOutOfRangeException("NumSides")
- End If
- ' Create a byte array to hold the random value.
- Dim randomNumber(0) As Byte
- Do
- ' Fill the array with a random value.
- rngCsp.GetBytes(randomNumber)
- Loop While Not IsFairRoll(randomNumber(0), numberSides)
- ' Return the random number mod the number
- ' of sides. The possible values are zero-
- ' based, so we add one.
- Return System.Convert.ToByte(randomNumber(0) Mod numberSides + 1)
- End Function
- Private Shared Function IsFairRoll(ByVal roll As Byte, ByVal numSides As Byte) As Boolean
- ' There are MaxValue / numSides full sets of numbers that can come up
- ' in a single byte. For instance, if we have a 6 sided die, there are
- ' 42 full sets of 1-6 that come up. The 43rd set is incomplete.
- Dim fullSetsOfValues As Integer = [Byte].MaxValue / numSides
- ' If the roll is within this range of fair values, then we let it continue.
- ' In the 6 sided die case, a roll between 0 and 251 is allowed. (We use
- ' < rather than <= since the = portion allows through an extra 0 value).
- ' 252 through 255 would provide an extra 0, 1, 2, 3 so they are not fair
- ' to use.
- Return roll < numSides * fullSetsOfValues
- End Function 'IsFairRoll
- End Class
- Imports System
- Imports System.IO
- Imports System.Text
- Imports System.Security.Cryptography
- Public Class rfc2898test
- ' Generate a key k1 with password pwd1 and salt salt1.
- ' Generate a key k2 with password pwd1 and salt salt1.
- ' Encrypt data1 with key k1 using symmetric encryption, creating edata1.
- ' Decrypt edata1 with key k2 using symmetric decryption, creating data2.
- ' data2 should equal data1.
- Private Const usageText As String = "Usage: RFC2898 <password>" + vbLf + "You must specify the password for encryption." + vbLf
- Public Shared Sub Main(ByVal passwordargs() As String)
- 'If no file name is specified, write usage text.
- If passwordargs.Length = 0 Then
- Console.WriteLine(usageText)
- Else
- Dim pwd1 As String = passwordargs(0)
- Dim salt1(8) As Byte
- Using rngCsp As New RNGCryptoServiceProvider()
- rngCsp.GetBytes(salt1)
- End Using
- 'data1 can be a string or contents of a file.
- Dim data1 As String = "Some test data"
- 'The default iteration count is 1000 so the two methods use the same iteration count.
- Dim myIterations As Integer = 1000
- Try
- Dim k1 As New Rfc2898DeriveBytes(pwd1, salt1, myIterations)
- Dim k2 As New Rfc2898DeriveBytes(pwd1, salt1)
- ' Encrypt the data.
- Dim encAlg As TripleDES = TripleDES.Create()
- encAlg.Key = k1.GetBytes(16)
- Dim encryptionStream As New MemoryStream()
- Dim encrypt As New CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write)
- Dim utfD1 As Byte() = New System.Text.UTF8Encoding(False).GetBytes(data1)
- encrypt.Write(utfD1, 0, utfD1.Length)
- encrypt.FlushFinalBlock()
- encrypt.Close()
- Dim edata1 As Byte() = encryptionStream.ToArray()
- k1.Reset()
- ' Try to decrypt, thus showing it can be round-tripped.
- Dim decAlg As TripleDES = TripleDES.Create()
- decAlg.Key = k2.GetBytes(16)
- decAlg.IV = encAlg.IV
- Dim decryptionStreamBacking As New MemoryStream()
- Dim decrypt As New CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write)
- decrypt.Write(edata1, 0, edata1.Length)
- decrypt.Flush()
- decrypt.Close()
- k2.Reset()
- Dim data2 As String = New UTF8Encoding(False).GetString(decryptionStreamBacking.ToArray())
- If Not data1.Equals(data2) Then
- Console.WriteLine("Error: The two values are not equal.")
- Else
- Console.WriteLine("The two values are equal.")
- Console.WriteLine("k1 iterations: {0}", k1.IterationCount)
- Console.WriteLine("k2 iterations: {0}", k2.IterationCount)
- End If
- Catch e As Exception
- Console.WriteLine("Error: ", e)
- End Try
- End If
- End Sub
- End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement