Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module RC2PSample
Sub Main()
Try
Dim RC2alg As RC2 = RC2.Create("RC2")
Dim sData As String = "this is a test."
Dim Data As Byte() = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV)
Dim Final As String = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV)
Console.WriteLine(Final)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
Try
Dim mStream As New MemoryStream
Dim RC2alg As RC2 = RC2.Create
Dim cStream As New CryptoStream(mStream,RC2alg.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
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
Try
Dim msDecrypt As New MemoryStream(Data)
Dim RC2alg As RC2 = RC2.Create
Dim csDecrypt As New CryptoStream(msDecrypt,RC2alg.CreateDecryptor(Key, IV),CryptoStreamMode.Read)
Dim fromEncrypt(Data.Length) As Byte
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
Return New ASCIIEncoding().GetString(fromEncrypt)
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Module
|