Advertisement
ZeekoSec

asd

Apr 7th, 2015
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.66 KB | None | 0 0
  1. Imports System
  2. Imports System.IO
  3. Imports System.Security.Cryptography
  4.  
  5. Public Class HMACSHA5126example
  6.  
  7. Public Shared Sub Main(ByVal Fileargs() As String)
  8. Dim dataFile As String
  9. Dim signedFile As String
  10. 'If no file names are specified, create them.
  11. If Fileargs.Length < 2 Then
  12. dataFile = "text.txt"
  13. signedFile = "signedFile.enc"
  14.  
  15. If Not File.Exists(dataFile) Then
  16. ' Create a file to write to.
  17. Using sw As StreamWriter = File.CreateText(dataFile)
  18. sw.WriteLine("Here is a message to sign")
  19. End Using
  20. End If
  21.  
  22. Else
  23. dataFile = Fileargs(0)
  24. signedFile = Fileargs(1)
  25. End If
  26. Try
  27. ' Create a random key using a random number generator. This would be the
  28. ' secret key shared by sender and receiver.
  29. Dim secretkey() As Byte = New [Byte](63) {}
  30. 'RNGCryptoServiceProvider is an implementation of a random number generator.
  31. Using rng As New RNGCryptoServiceProvider()
  32. ' The array is now filled with cryptographically strong random bytes.
  33. rng.GetBytes(secretkey)
  34.  
  35. ' Use the secret key to encode the message file.
  36. SignFile(secretkey, dataFile, signedFile)
  37.  
  38. ' Take the encoded file and decode
  39. VerifyFile(secretkey, signedFile)
  40. End Using
  41. Catch e As IOException
  42. Console.WriteLine("Error: File not found", e)
  43. End Try
  44.  
  45. End Sub 'Main
  46.  
  47. ' Computes a keyed hash for a source file and creates a target file with the keyed hash
  48. ' prepended to the contents of the source file.
  49. Public Shared Sub SignFile(ByVal key() As Byte, ByVal sourceFile As String, ByVal destFile As String)
  50. ' Initialize the keyed hash object.
  51. Using myhmac As New HMACSHA512(key)
  52. Using inStream As New FileStream(sourceFile, FileMode.Open)
  53. Using outStream As New FileStream(destFile, FileMode.Create)
  54. ' Compute the hash of the input file.
  55. Dim hashValue As Byte() = myhmac.ComputeHash(inStream)
  56. ' Reset inStream to the beginning of the file.
  57. inStream.Position = 0
  58. ' Write the computed hash value to the output file.
  59. outStream.Write(hashValue, 0, hashValue.Length)
  60. ' Copy the contents of the sourceFile to the destFile.
  61. Dim bytesRead As Integer
  62. ' read 1K at a time
  63. Dim buffer(1023) As Byte
  64. Do
  65. ' Read from the wrapping CryptoStream.
  66. bytesRead = inStream.Read(buffer, 0, 1024)
  67. outStream.Write(buffer, 0, bytesRead)
  68. Loop While bytesRead > 0
  69. End Using
  70. End Using
  71. End Using
  72. Return
  73.  
  74. End Sub 'SignFile
  75. ' end SignFile
  76.  
  77. ' Compares the key in the source file with a new key created for the data portion of the file. If the keys
  78. ' compare the data has not been tampered with.
  79. Public Shared Function VerifyFile(ByVal key() As Byte, ByVal sourceFile As String) As Boolean
  80. Dim err As Boolean = False
  81. ' Initialize the keyed hash object.
  82. Using hmac As New HMACSHA512(key)
  83. ' Create an array to hold the keyed hash value read from the file.
  84. Dim storedHash(hmac.HashSize / 8) As Byte
  85. ' Create a FileStream for the source file.
  86. Using inStream As New FileStream(sourceFile, FileMode.Open)
  87. ' Read in the storedHash.
  88. inStream.Read(storedHash, 0, storedHash.Length - 1)
  89. ' Compute the hash of the remaining contents of the file.
  90. ' The stream is properly positioned at the beginning of the content,
  91. ' immediately after the stored hash value.
  92. Dim computedHash As Byte() = hmac.ComputeHash(inStream)
  93. ' compare the computed hash with the stored value
  94. Dim i As Integer
  95. For i = 0 To storedHash.Length - 2
  96. If computedHash(i) <> storedHash(i) Then
  97. err = True
  98. End If
  99. Next i
  100. End Using
  101. End Using
  102. If err Then
  103. Console.WriteLine("Hash values differ! Signed file has been tampered with!")
  104. Return False
  105. Else
  106. Console.WriteLine("Hash values agree -- no tampering occurred.")
  107. Return True
  108. End If
  109.  
  110. End Function 'VerifyFile
  111. End Class 'HMACSHA5126example 'end VerifyFile
  112. 'end class
  113.  
  114. 'The following sample uses the Cryptography class to simulate the roll of a dice.
  115. Imports System
  116. Imports System.IO
  117. Imports System.Text
  118. Imports System.Security.Cryptography
  119.  
  120.  
  121.  
  122. Class RNGCSP
  123. Private Shared rngCsp As New RNGCryptoServiceProvider()
  124. ' Main method.
  125. Public Shared Sub Main()
  126. Const totalRolls As Integer = 25000
  127. Dim results(5) As Integer
  128.  
  129. ' Roll the dice 25000 times and display
  130. ' the results to the console.
  131. Dim x As Integer
  132. For x = 0 To totalRolls
  133. Dim roll As Byte = RollDice(System.Convert.ToByte(results.Length))
  134. results((roll - 1)) += 1
  135. Next x
  136. Dim i As Integer
  137.  
  138. While i < results.Length
  139. Console.WriteLine("{0}: {1} ({2:p1})", i + 1, results(i), System.Convert.ToDouble(results(i)) / System.Convert.ToDouble(totalRolls))
  140. i += 1
  141. End While
  142. rngCsp.Dispose()
  143. Console.ReadLine()
  144. End Sub
  145.  
  146.  
  147. ' This method simulates a roll of the dice. The input parameter is the
  148. ' number of sides of the dice.
  149. Public Shared Function RollDice(ByVal numberSides As Byte) As Byte
  150. If numberSides <= 0 Then
  151. Throw New ArgumentOutOfRangeException("NumSides")
  152. End If
  153. ' Create a byte array to hold the random value.
  154. Dim randomNumber(0) As Byte
  155. Do
  156. ' Fill the array with a random value.
  157. rngCsp.GetBytes(randomNumber)
  158. Loop While Not IsFairRoll(randomNumber(0), numberSides)
  159. ' Return the random number mod the number
  160. ' of sides. The possible values are zero-
  161. ' based, so we add one.
  162. Return System.Convert.ToByte(randomNumber(0) Mod numberSides + 1)
  163.  
  164. End Function
  165.  
  166.  
  167. Private Shared Function IsFairRoll(ByVal roll As Byte, ByVal numSides As Byte) As Boolean
  168. ' There are MaxValue / numSides full sets of numbers that can come up
  169. ' in a single byte. For instance, if we have a 6 sided die, there are
  170. ' 42 full sets of 1-6 that come up. The 43rd set is incomplete.
  171. Dim fullSetsOfValues As Integer = [Byte].MaxValue / numSides
  172.  
  173. ' If the roll is within this range of fair values, then we let it continue.
  174. ' In the 6 sided die case, a roll between 0 and 251 is allowed. (We use
  175. ' < rather than <= since the = portion allows through an extra 0 value).
  176. ' 252 through 255 would provide an extra 0, 1, 2, 3 so they are not fair
  177. ' to use.
  178. Return roll < numSides * fullSetsOfValues
  179.  
  180. End Function 'IsFairRoll
  181. End Class
  182.  
  183. Imports System
  184. Imports System.IO
  185. Imports System.Text
  186. Imports System.Security.Cryptography
  187.  
  188.  
  189.  
  190. Public Class rfc2898test
  191. ' Generate a key k1 with password pwd1 and salt salt1.
  192. ' Generate a key k2 with password pwd1 and salt salt1.
  193. ' Encrypt data1 with key k1 using symmetric encryption, creating edata1.
  194. ' Decrypt edata1 with key k2 using symmetric decryption, creating data2.
  195. ' data2 should equal data1.
  196. Private Const usageText As String = "Usage: RFC2898 <password>" + vbLf + "You must specify the password for encryption." + vbLf
  197.  
  198. Public Shared Sub Main(ByVal passwordargs() As String)
  199. 'If no file name is specified, write usage text.
  200. If passwordargs.Length = 0 Then
  201. Console.WriteLine(usageText)
  202. Else
  203. Dim pwd1 As String = passwordargs(0)
  204.  
  205. Dim salt1(8) As Byte
  206. Using rngCsp As New RNGCryptoServiceProvider()
  207. rngCsp.GetBytes(salt1)
  208. End Using
  209. 'data1 can be a string or contents of a file.
  210. Dim data1 As String = "Some test data"
  211. 'The default iteration count is 1000 so the two methods use the same iteration count.
  212. Dim myIterations As Integer = 1000
  213. Try
  214. Dim k1 As New Rfc2898DeriveBytes(pwd1, salt1, myIterations)
  215. Dim k2 As New Rfc2898DeriveBytes(pwd1, salt1)
  216. ' Encrypt the data.
  217. Dim encAlg As TripleDES = TripleDES.Create()
  218. encAlg.Key = k1.GetBytes(16)
  219. Dim encryptionStream As New MemoryStream()
  220. Dim encrypt As New CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write)
  221. Dim utfD1 As Byte() = New System.Text.UTF8Encoding(False).GetBytes(data1)
  222. encrypt.Write(utfD1, 0, utfD1.Length)
  223. encrypt.FlushFinalBlock()
  224. encrypt.Close()
  225. Dim edata1 As Byte() = encryptionStream.ToArray()
  226. k1.Reset()
  227.  
  228. ' Try to decrypt, thus showing it can be round-tripped.
  229. Dim decAlg As TripleDES = TripleDES.Create()
  230. decAlg.Key = k2.GetBytes(16)
  231. decAlg.IV = encAlg.IV
  232. Dim decryptionStreamBacking As New MemoryStream()
  233. Dim decrypt As New CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write)
  234. decrypt.Write(edata1, 0, edata1.Length)
  235. decrypt.Flush()
  236. decrypt.Close()
  237. k2.Reset()
  238. Dim data2 As String = New UTF8Encoding(False).GetString(decryptionStreamBacking.ToArray())
  239.  
  240. If Not data1.Equals(data2) Then
  241. Console.WriteLine("Error: The two values are not equal.")
  242. Else
  243. Console.WriteLine("The two values are equal.")
  244. Console.WriteLine("k1 iterations: {0}", k1.IterationCount)
  245. Console.WriteLine("k2 iterations: {0}", k2.IterationCount)
  246. End If
  247. Catch e As Exception
  248. Console.WriteLine("Error: ", e)
  249. End Try
  250. End If
  251.  
  252. End Sub
  253. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement