TizzyT

XorUInt64 -TizzyT

Jul 6th, 2015
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.88 KB | None | 0 0
  1.     Public Structure XorUInt64
  2.         Private Shared Rnd As Random
  3.         Private StoredValue As UInt64
  4.         Private TokenHash ,ValueHash As Byte
  5.         Private Function RndUInt64() As UInt64
  6.             Dim ULongBytes(7) As Byte
  7.             Rnd.NextBytes(ULongBytes)
  8.             Return BitConverter.ToUInt64(ULongBytes, 0)
  9.         End Function
  10.         Private Function Hash(ByVal Token As UInt64) As Byte
  11.             Dim TokenBytes() As Byte = BitConverter.GetBytes(Token)
  12.             Dim HashCode As Int16 = TokenBytes(0)
  13.             HashCode += TokenBytes(1) Xor 170
  14.             HashCode += TokenBytes(2) Xor 170
  15.             HashCode += TokenBytes(3) Xor 170
  16.             HashCode += TokenBytes(4) Xor 170
  17.             HashCode += TokenBytes(5) Xor 170
  18.             HashCode += TokenBytes(6) Xor 170
  19.             HashCode += TokenBytes(7) Xor 170
  20.             Return HashCode Mod 256
  21.         End Function
  22.         Public Sub New(ByRef Token As UInt64)
  23.             Rnd = New Random
  24.             Token = RndUInt64()
  25.             TokenHash = Hash(Token)
  26.         End Sub
  27.         Public Sub Store(ByRef Token As UInt64, ByVal Value As UInt64)
  28.             If Hash(Token) = TokenHash Then
  29.                 Token = RndUInt64()
  30.                 TokenHash = Hash(Token)
  31.                 ValueHash = Hash(Value)
  32.                 StoredValue = Token Xor Value
  33.             Else
  34.                 Throw New Exception("Token hash mismatch")
  35.             End If
  36.         End Sub
  37.         Default Public ReadOnly Property Value(ByVal Token As UInt64) As UInt64
  38.             Get
  39.                 If Hash(Token) <> TokenHash Then Throw New Exception("Token hash mismatch")
  40.                 Dim R As UInt64 = StoredValue Xor Token
  41.                 If Hash(R) = ValueHash Then Return R Else Throw New Exception("Return value inconsistent with stored value")
  42.             End Get
  43.         End Property
  44.     End Structure
Advertisement
Add Comment
Please, Sign In to add comment