Imports System.Security.Cryptography
Imports System.IO

Module Globals
    ' To generate these arrays please use KeyGen application included into this sample
    Dim Key As Byte() = {&H9B, &H67, &H14, &HC, &HB8, &H7E, &HF0, &H4B, &H6E, &HD, &H88, &H7A, &HF1, &HBB, &H33, &HC1, &HC1, &H12, &HA3, &H1F, &HCA, &H2D, &HDC, &H54}
    Dim IV As Byte() = {&H3D, &H12, &HE9, &H8C, &HEA, &H24, &H61, &HF0}

    ' As it's impossible to move pointer of CryptoStream to any position we split input data into chunks
    ' and crypt each chunk
    Public ChunkSize As Integer = 1024 * 1024

    Public Function Encrypt(ByVal input() As Byte, ByVal size As Integer) As Byte()
        Dim TDES As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider

        Using EncryptedDataStream As MemoryStream = New MemoryStream
            Using CryptoStream As CryptoStream = New CryptoStream(EncryptedDataStream, TDES.CreateEncryptor(Globals.Key, Globals.IV), CryptoStreamMode.Write)
                CryptoStream.Write(input, 0, size)
                CryptoStream.FlushFinalBlock()

                Dim output(EncryptedDataStream.Length - 1) As Byte
                EncryptedDataStream.Position = 0
                EncryptedDataStream.Read(output, 0, output.Length)

                Encrypt = output
            End Using
        End Using
    End Function

    Public Function Decrypt(ByVal input() As Byte, ByVal size As Integer) As Byte()
        Dim TDES As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider

        Using EncryptedDataStream As MemoryStream = New MemoryStream(input)
            Using CryptoStream As CryptoStream = New CryptoStream(EncryptedDataStream, TDES.CreateDecryptor(Globals.Key, Globals.IV), CryptoStreamMode.Read)
                Dim output(size - 1) As Byte
                CryptoStream.Read(output, 0, size)
                Decrypt = output
            End Using
        End Using
    End Function
End Module
