Encrypting a file : Cypher Decypher File « File Directory « VB.Net






Encrypting a file

  

Imports System.Security.Cryptography
Module MainModule
    Public Function GenerateKey() As Byte()
        Dim objDES As New System.Security.Cryptography.DESCryptoServiceProvider()
        objDES.GenerateKey()
        Return objDES.Key
    End Function

    Public Function GenerateIV() As Byte()
        Dim objDES As New System.Security.Cryptography.DESCryptoServiceProvider()
        objDES.GenerateIV()
        Return objDES.IV
    End Function

    Public Sub SaveEncryptedFile(ByVal Key() As Byte, ByVal IV() As Byte, ByVal Data As String, ByVal Filename As String)
        Dim objFileStream As New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        Dim bytInput As Byte() = New System.Text.UnicodeEncoding().GetBytes(Data)
        Dim objDES As New DESCryptoServiceProvider()
        objDES.Key = Key
        objDES.IV = IV

        Dim objDESEncrypt As ICryptoTransform = objDES.CreateEncryptor()
        Dim objCryptStream As New CryptoStream(objFileStream, objDESEncrypt, CryptoStreamMode.Write)
        objCryptStream.Write(bytInput, 0, bytInput.Length)
        objCryptStream.Close()
        objFileStream.Close()

    End Sub

    Public Function LoadEncryptedFile(ByVal Key() As Byte, ByVal IV() As Byte, ByVal Filename As String) As String
        Dim objFileStream As New System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)
        Dim objDES As New DESCryptoServiceProvider()
        objDES.Key = Key
        objDES.IV = IV

        Dim objDESDecrypt As ICryptoTransform = objDES.CreateDecryptor()
        Dim objCryptStream As New CryptoStream(objFileStream, objDESDecrypt, CryptoStreamMode.Read)
        LoadEncryptedFile = New System.IO.StreamReader(objCryptStream, New System.Text.UnicodeEncoding()).ReadToEnd()
        objCryptStream.Close()
        objFileStream.Close()
    End Function

End Module

   
    
  








Related examples in the same category

1.Use DES, RC2, Rijndael, TripleDES to decrypt and Encrypt filesUse DES, RC2, Rijndael, TripleDES to decrypt and Encrypt files
2.Decrypt a Des Encryted File
3.Use Des to cypher and decypher File Use Des to cypher and decypher File