Triple DES (3DES) is the common name for the Triple Data Encryption Algorithm (TDEA or Triple DEA) symmetric-key block cipher, which applies the Data Encryption Standard (DES) cipher algorithm three times to each data block.
Namespace:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Code:
Friend Class cTripleDES
' Triple DES provider
Private Obj_Des As New TripleDESCryptoServiceProvider
' String handler
Private Obj_Utf8 As New UTF8Encoding
Private Key() As Byte
Private Init_Vec() As Byte
Public Sub New(ByVal key() As Byte, ByVal iv() As Byte)
Me.Key = key
Me.Init_Vec = iv
End Sub
Public Function Encrypt(ByVal input() As Byte) As Byte()
Return ConvertTO(input, Obj_Des.CreateEncryptor(Key, Init_Vec))
End Function
Public Function Decrypt(ByVal input() As Byte) As Byte()
Return ConvertTO(input, Obj_Des.CreateDecryptor(Key, Init_Vec))
End Function
Public Function Encrypt(ByVal text As String) As String
Dim input() As Byte = Obj_Utf8.GetBytes(text)
Dim output() As Byte = ConvertTO(input, _
Obj_Des.CreateEncryptor(Key, Init_Vec))
Return Convert.ToBase64String(output)
End Function
Public Function Decrypt(ByVal text As String) As String
Dim input() As Byte = Convert.FromBase64String(text)
Dim output() As Byte = ConvertTO(input, _
Obj_Des.CreateDecryptor(Key, Init_Vec))
Return Obj_Utf8.GetString(output)
End Function
Private Function ConvertTO(ByVal input() As Byte, _
ByVal CryptoTransform As ICryptoTransform) As Byte()
' create the necessary streams
Dim memStream As MemoryStream = New MemoryStream
Dim cryptStream As CryptoStream = New _
CryptoStream(memStream, CryptoTransform, _
CryptoStreamMode.Write)
cryptStream.Write(input, 0, input.Length)
cryptStream.FlushFinalBlock()
memStream.Position = 0
Dim result(CType(memStream.Length - 1, System.Int32)) As Byte
memStream.Read(result, 0, CType(result.Length, System.Int32))
memStream.Close()
cryptStream.Close()
Return result
End Function
End Class