Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module RC2Sample
Sub Main()
Try
Dim RC2alg As RC2 = RC2.Create("RC2")
Dim sData As String = "this is a test"
Dim FileName As String = "CText.txt"
EncryptTextToFile(sData, FileName, RC2alg.Key, RC2alg.IV)
Dim Final As String = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.IV)
Console.WriteLine(Final)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
Try
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim RC2alg As RC2 = RC2.Create
Dim cStream As New CryptoStream(fStream,RC2alg.CreateEncryptor(Key, IV),CryptoStreamMode.Write)
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(Data)
sWriter.Close()
cStream.Close()
fStream.Close()
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Catch e As UnauthorizedAccessException
Console.WriteLine("A file error occurred: {0}", e.Message)
End Try
End Sub
Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
Try
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim RC2alg As RC2 = RC2.Create
Dim cStream As New CryptoStream(fStream,RC2alg.CreateDecryptor(Key, IV),CryptoStreamMode.Read)
Dim sReader As New StreamReader(cStream)
Dim val As String = sReader.ReadLine()
sReader.Close()
cStream.Close()
fStream.Close()
Return val
Catch e As CryptographicException
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
Return Nothing
Catch e As UnauthorizedAccessException
Console.WriteLine("A file error occurred: {0}", e.Message)
Return Nothing
End Try
End Function
End Module