CryptoStream Class Defines a stream that links data streams to cryptographic transformations. : CryptoStream « File Directory « VB.Net






CryptoStream Class Defines a stream that links data streams to cryptographic transformations.

 

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RijndaelSample
    Sub Main()
        Try
            Dim RijndaelAlg As Rijndael = Rijndael.Create
            Dim sData As String = "this is a test."
            Dim FileName As String = "CText.txt"
            EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV)
            Dim Final As String = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.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 RijndaelAlg As Rijndael = Rijndael.Create
            Dim cStream As New CryptoStream(fStream, _
                                           RijndaelAlg.CreateEncryptor(Key, IV), _
                                           CryptoStreamMode.Write)

            Dim sWriter As New StreamWriter(cStream)
            Try
                sWriter.WriteLine(Data)
            Catch e As Exception
                Console.WriteLine("An error occurred: {0}", e.Message)
            Finally
                sWriter.Close()
                cStream.Close()
                fStream.Close()
            End Try
        Catch e As Exception
            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 RijndaelAlg As Rijndael = Rijndael.Create
            Dim cStream As New CryptoStream(fStream, _
                                            RijndaelAlg.CreateDecryptor(Key, IV), _
                                            CryptoStreamMode.Read)
            Dim sReader As New StreamReader(cStream)
            Dim val As String = Nothing
            Try
                val = sReader.ReadLine()
            Catch e As Exception
                Console.WriteLine("An Cerror occurred: {0}", e.Message)
            Finally
                sReader.Close()
                cStream.Close()
                fStream.Close()
            End Try
            Return val
        Catch e As Exception
            Console.WriteLine("A file error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module

   
  








Related examples in the same category