vrijdag 26 september 2008

Encryption in VB.NET

Encryption in Visual Basic .NET has become quite simple, as the .NET Framework already includes some popular encryption providers. The following class makes it easier to use encryption in your application.

Public Class CryptTools
Private Shared HashKey As Byte() = {12, 45, 7, 123, 6, 34, 56, 12, 245, 34}

Public Shared Function GetHexHash(ByVal ba As Byte()) As String
Dim hb As String
Dim ret As String = ""

For i As Integer = 0 To ba.Length - 1
hb = Hex(ba(i))
If hb.Length = 0 Then
hb = "00"
ElseIf hb.Length = 1 Then
hb = "0" & hb
End If

ret &= hb
Next

Return ret
End Function

Public Shared Function Encrypt(ByVal data As String, ByVal key As String) As Byte()
Return Encrypt(System.Text.ASCIIEncoding.ASCII.GetBytes(data), key)
End Function

Public Shared Function Encrypt(ByRef data As Byte(), ByVal key As String) As Byte()
Dim RMCrypto As New System.Security.Cryptography.RijndaelManaged
Dim mStream As System.IO.MemoryStream
Dim CryptStream As System.Security.Cryptography.CryptoStream
Dim bytIV() As Byte = {115, 21, 106, 15, 12, 78, 19, 30, 200, 90, 40, 75, 13, 212, 21, 67}
Dim bytKEY() As Byte
Dim sha As New System.Security.Cryptography.HMACSHA256(HashKey)

'Create key from the hash of the string
bytKEY = sha.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))

'Encrypt the data
mStream = New IO.MemoryStream()
RMCrypto.KeySize = 256
CryptStream = New System.Security.Cryptography.CryptoStream(mStream, RMCrypto.CreateEncryptor(bytKEY, bytIV), System.Security.Cryptography.CryptoStreamMode.Write)
CryptStream.Write(data, 0, data.Length)
CryptStream.FlushFinalBlock()

'Cean up
CryptStream.Close()
mStream.Close()

Return mStream.ToArray()
End Function

Public Shared Function Decrypt(ByVal data As String, ByVal key As String) As Byte()
Return Decrypt(System.Text.ASCIIEncoding.ASCII.GetBytes(data), key)
End Function

Public Shared Function Decrypt(ByRef data As Byte(), ByVal key As String) As Byte()
Dim RMCrypto As New System.Security.Cryptography.RijndaelManaged
Dim mStream As System.IO.MemoryStream
Dim CryptStream As System.Security.Cryptography.CryptoStream
Dim cryptBuffer As Byte()
Dim bytIV() As Byte = {115, 21, 106, 15, 12, 78, 19, 30, 200, 90, 40, 75, 13, 212, 21, 67}
Dim bytKEY() As Byte
Dim sha As New System.Security.Cryptography.HMACSHA256(HashKey)

'Create key from the hash of the string
bytKEY = sha.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key))

'Encrypt the data
mStream = New IO.MemoryStream(data)
RMCrypto.KeySize = 256
CryptStream = New System.Security.Cryptography.CryptoStream(mStream, RMCrypto.CreateDecryptor(bytKEY, bytIV), System.Security.Cryptography.CryptoStreamMode.Read)
ReDim cryptBuffer(data.Length - 1)
CryptStream.Read(cryptBuffer, 0, data.Length)

'Cean up
CryptStream.Close()
mStream.Close()

Return cryptBuffer
End Function

End Class