Use Des to cypher and decypher File
Imports System
Imports System.Windows.Forms
Imports System.Security
Imports System.Security.Cryptography
Imports System.IO
Public Class MainClass
Shared Sub Main()
Dim plainTextFileName As String = "test.txt"
Dim cypherTextFileName As String = "cyphertext.dat"
Dim decypheredFileName As String = "decyphered.txt"
CryptFile("MyPassword", plainTextFileName, cypherTextFileName, True)
Console.WriteLine( File.ReadAllText(plainTextFileName))
Console.WriteLine( File.ReadAllText(cypherTextFileName))
CryptFile("MyPassword", cypherTextFileName, decypheredFileName, False)
Console.WriteLine( File.ReadAllText(decypheredFileName))
End Sub
' Encrypt or decrypt a file, saving the results
' in another file.
Shared Private Sub CryptFile(ByVal password As String, ByVal in_file As String, ByVal out_file As String, ByVal encrypt As Boolean)
' Create input and output file streams.
Dim in_stream As New FileStream(in_file, FileMode.Open, FileAccess.Read)
Dim out_stream As New FileStream(out_file, FileMode.Create, FileAccess.Write)
Dim des_provider As New TripleDESCryptoServiceProvider()
' Find a valid key size for this provider.
Dim key_size_bits As Integer = 0
For i As Integer = 1024 To 1 Step -1
If des_provider.ValidKeySize(i) Then
key_size_bits = i
Exit For
End If
Next i
'Debug.Assert(key_size_bits > 0)
Dim block_size_bits As Integer = des_provider.BlockSize
Dim key As Byte() = Nothing
Dim iv As Byte() = Nothing
MakeKeyAndIV(password, key_size_bits, block_size_bits, key, iv)
Dim crypto_transform As ICryptoTransform
If encrypt Then
crypto_transform = des_provider.CreateEncryptor(key, iv)
Else
crypto_transform = des_provider.CreateDecryptor(key, iv)
End If
Dim crypto_stream As New CryptoStream(out_stream, crypto_transform, CryptoStreamMode.Write)
Const BLOCK_SIZE As Integer = 1024
Dim buffer(BLOCK_SIZE) As Byte
Dim bytes_read As Integer
Do
bytes_read = in_stream.Read(buffer, 0, BLOCK_SIZE)
If bytes_read = 0 Then Exit Do
crypto_stream.Write(buffer, 0, bytes_read)
Loop
crypto_stream.Close()
in_stream.Close()
out_stream.Close()
End Sub
' Use the password to generate key bytes.
Shared Private Sub MakeKeyAndIV(ByVal password As String, ByVal key_size_bits As Integer, ByVal block_size_bits As Integer, ByRef key As Byte(), ByRef iv As Byte())
Dim password_derive_bytes As New PasswordDeriveBytes( _
"MyPassword", Nothing, "SHA384", 1000)
key = password_derive_bytes.GetBytes(key_size_bits \ 8)
iv = password_derive_bytes.GetBytes(block_size_bits \ 8)
End Sub
End Class
Related examples in the same category