Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module DESCSPSample
Sub Main()
Dim DESalg As New DESCryptoServiceProvider
Dim sData As String = "Here is some data to encrypt."
Dim Data As Byte() = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV)
Dim Final As String = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV)
Console.WriteLine(Final)
End Sub
Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
Dim mStream As New MemoryStream
Dim cStream As New CryptoStream(mStream,New DESCryptoServiceProvider().CreateEncryptor(Key, IV),CryptoStreamMode.Write)
Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data)
cStream.Write(toEncrypt, 0, toEncrypt.Length)
cStream.FlushFinalBlock()
Dim ret As Byte() = mStream.ToArray()
cStream.Close()
mStream.Close()
Return ret
End Function
Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
Dim msDecrypt As New MemoryStream(Data)
Dim csDecrypt As New CryptoStream(msDecrypt,New DESCryptoServiceProvider().CreateDecryptor(Key, IV),CryptoStreamMode.Read)
Dim fromEncrypt(Data.Length) As Byte
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
Return New ASCIIEncoding().GetString(fromEncrypt)
End Function
End Module
|