Public Class TripleDES
Private _k, _iv As Byte()
Public Sub New(ByVal key As Byte(), ByVal iv As Byte())
_k = key
_iv = iv
End Sub
Public Property Key() As Byte()
Get
Return _k
End Get
Set(ByVal value As Byte())
_k = value
End Set
End Property
Public Property IV() As Byte()
Get
Return _iv
End Get
Set(ByVal value As Byte())
_iv = value
End Set
End Property
Public Function Encrypt(ByVal plaintext As String) As String
Dim cipher As New System.Security.Cryptography.TripleDESCryptoServiceProvider()
cipher.BlockSize = 64
Dim cipherText As String
Using cipherTextStream As New IO.MemoryStream()
Using cryptoStream As New System.Security.Cryptography.CryptoStream(cipherTextStream, cipher.CreateEncryptor(_k, _iv), System.Security.Cryptography.CryptoStreamMode.Write)
Dim bytes As Byte() = Text.Encoding.UTF8.GetBytes(plaintext)
cryptoStream.Write(bytes, 0, bytes.Length)
cryptoStream.FlushFinalBlock()
cipherText = Convert.ToBase64String(cipherTextStream.ToArray())
End Using
End Using
Return cipherText
End Function
Public Function Decrypt(ByVal ciphertext As String) As String
Dim cipher As New System.Security.Cryptography.TripleDESCryptoServiceProvider()
cipher.BlockSize = 64
Dim plaintext As String
Using plaintextStream As New IO.MemoryStream()
Using cryptoStream As New System.Security.Cryptography.CryptoStream(plaintextStream, cipher.CreateDecryptor(_k, _iv), System.Security.Cryptography.CryptoStreamMode.Write)
Dim bytes As Byte() = Convert.FromBase64String(ciphertext)
cryptoStream.Write(bytes, 0, bytes.Length)
cryptoStream.FlushFinalBlock()
plaintext = Text.Encoding.UTF8.GetString(plaintextStream.ToArray())
End Using
End Using
Return plaintext
End Function
End Class
To use it, simply instanciate it with your Key and Initialization Vector. Make sure your K and IV are the same when decrypting data you encrypted with them!- Published on
Using .NET TripleDES Crypto Provider
- Authors
- Name
- Craig Wardman
I recently wrote a wrapper class implementing the .NET System.Security.Cryptography.TripleDESCryptoServiceProvider to quickly allow you to encrypt a plaintext string and return the Base64 encoded string of the encrypted bytes created by the TripleDES cipher (and decrypt that string back to plaintext!).
This provides a very simple way to encrypt and decrypt your data without the need to store it as a binary image.
The VB.NET code is shown below: