Hi there,
This is my first post on this forum, so thank you in advance for any help you can provide. I based this code around a post taken from a user of code project and it has been perfect for my needs, however I would like to add compression before the actually encryption takes place and I was wondering if anyone could help as I am totally stuck.
I have added a DeflateStream but I simply do not understand how to progress from this point. Thanks in advance.
Public Class Encryption
Dim fsInput As System.IO.FileStream
Dim fsOutput As System.IO.FileStream
Public Sub EncryptOrDecryptFile(ByVal strInputFile As String, ByVal strOutputFile As String, ByVal bytKey() As Byte, ByVal bytIV() As Byte, ByVal Direction As CryptoAction, Optional ByRef pbStatus As ProgressBar = Nothing)
'Setup file streams to handle input and output.
fsInput = New System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read)
fsOutput = New System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write)
fsOutput.SetLength(0) 'make sure fsOutput is empty
'Declare variables for encrypt/decrypt process.
Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing
Dim lngFileLength As Long = fsInput.Length 'the input file's length
Dim lngBytesProcessed As Long = 0 'running count of bytes processed
Dim intBytesInCurrentBlock As Integer 'current bytes being processed
Dim csCryptoStream As CryptoStream = Nothing
Dim CompStream As DeflateStream = Nothing
'Declare CryptoServiceProvider.
Dim cspRijndael As New RijndaelManaged
cspRijndael.KeySize = 256
cspRijndael.Padding = PaddingMode.ISO10126
cspRijndael.Mode = CipherMode.CBC
'Setup Progress Bar
If Not IsNothing(pbStatus) Then
pbStatus.Value = 0
pbStatus.Maximum = 100
End If
'Determine if ecryption or decryption and setup CryptoStream.
Select Case Direction
Case CryptoAction.ActionEncrypt
csCryptoStream = New CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write)
Case CryptoAction.ActionDecrypt
csCryptoStream = New CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write)
End Select
If Direction = CryptoAction.ActionEncrypt Then
CompStream = New DeflateStream(fsOutput, CompressionMode.Compress, False)
Else
CompStream = New DeflateStream(fsOutput, CompressionMode.Decompress, False)
End If
'Use Do While to loop until all of the file is processed.
Do While lngBytesProcessed < lngFileLength
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096) 'Read file with the input filestream.
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock) 'Write output file with the cryptostream.
lngBytesProcessed += CLng(intBytesInCurrentBlock) 'Update lngBytesProcessed
'Update Progress Bar
If Not IsNothing(pbStatus) Then
pbStatus.Value = CInt((lngBytesProcessed / lngFileLength) * 100)
End If
Loop
'Close FileStreams and CryptoStream.
csCryptoStream.Close()
fsInput.Close()
fsOutput.Close()
End Sub