Imports Microsoft.VisualBasic
Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Public Class TripleDESEncryption

  'Public Key() As Byte
  'Public Shared IV() As Byte

  Public Shared Function Encrypt(ByVal strData As String, ByVal key As Byte(), ByRef iv As Byte()) As Byte()
    Dim ms As New MemoryStream
    Dim cs As CryptoStream = Nothing
    Try
      Dim data() As Byte = ASCIIEncoding.ASCII.GetBytes(strData)
      Dim tdes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
      If key Is Nothing Then
        Return Nothing
      Else
        tdes.Key = key
      End If

      If iv Is Nothing Then
        tdes.GenerateIV()
        iv = tdes.IV
      Else
        tdes.IV = iv
      End If

      Dim encryptor As ICryptoTransform = tdes.CreateEncryptor()
      cs = New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
      cs.Write(data, 0, data.Length)
      cs.FlushFinalBlock()
      ms.Position = 0
      Dim result(CType(ms.Length - 1, Integer)) As Byte
      ms.Read(result, 0, CInt(ms.Length))
      Return result
    Catch ex As Exception
      Throw New ApplicationException("Cannot Encrypt")
    Finally
      ms.Close()
      If Not cs Is Nothing Then cs.Close()
    End Try
  End Function

  Public Shared Function Decrypt(ByVal data() As Byte, ByVal key As Byte(), ByRef iv As Byte()) As String
    Dim ms As New MemoryStream
    Dim cs As CryptoStream = Nothing
    Try
      Dim tdes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
      If key Is Nothing OrElse iv Is Nothing Then
        Return Nothing
      End If

      tdes.Key = key
      tdes.IV = iv


      Dim decryptor As ICryptoTransform = tdes.CreateDecryptor()

      cs = New CryptoStream(ms, decryptor, CryptoStreamMode.Write)
      cs.Write(data, 0, data.Length)
      cs.FlushFinalBlock()
      ms.Position = 0
      Dim result(CInt(ms.Length - 1)) As Byte
      ms.Read(result, 0, CInt(ms.Length))

      Return ASCIIEncoding.ASCII.GetString(result)
    Catch ex As Exception
      Throw New ApplicationException("Cannot Decrypt")
    Finally
      ms.Close()
      If Not cs Is Nothing Then cs.Close()
    End Try
  End Function

End Class
