Public Shared Function RijndaelEncryptDecrypt(ByVal source As String, ByVal destination As String, _
ByVal key As String, _
ByVal action As RijndaelCryptographicAction) _
As Boolean
RijndaelAlg.BlockSize = 256
GenerateOutput(source, destination, action)
Dim input As New FileStream(source, FileMode.Open, FileAccess.Read)
Dim output As New FileStream(destination, FileMode.OpenOrCreate)
Dim cStream As CryptoStream = Nothing
Dim Buffer(4096) As Byte
Dim CurrentBytes As Integer = 0
Dim BytesProcessed As Long = 0
Dim SourceLength As Long = input.Length
Dim PercentDone As Integer = 0
Dim _key As Byte() = CheckKey(key)
Dim IV As Byte() = GenerateIV(key)
Try
Select Case action
Case RijndaelCryptographicAction.Encrypt
If source.EndsWith(".encx") Then
output.Close()
input.Close()
File.Delete(destination)
RaiseEvent ReturnType(ActionReturnType.EncryptInvalidFileType)
Exit Try
End If
cStream = New CryptoStream(output, _
RijndaelAlg.CreateEncryptor(_key, IV), _
CryptoStreamMode.Write)
cStream.Write(HeaderBytes, 0, 5)
Do While BytesProcessed < SourceLength
CurrentBytes = input.Read(Buffer, 0, 4096)
cStream.Write(Buffer, 0, CurrentBytes)
BytesProcessed += CLng(CurrentBytes)
PercentDone = CInt((BytesProcessed / SourceLength) * 100)
RaiseEvent Progress(PercentDone)
Loop
Case RijndaelCryptographicAction.Decrypt
If Not source.EndsWith(".encx") Then
output.Close()
input.Close()
File.Delete(destination)
RaiseEvent ReturnType(ActionReturnType.DecryptInvalidFileType)
Exit Try
End If
cStream = New CryptoStream(input, _
RijndaelAlg.CreateDecryptor(_key, IV), _
CryptoStreamMode.Read)
Dim HeaderBuffer(4) As Byte
cStream.Read(HeaderBuffer, 0, 5)
If encoding.GetString(HeaderBuffer) <> HeaderString Then
RaiseEvent ReturnType(ActionReturnType.InvalidPassword)
cStream.Clear()
Exit Try
End If
Do While BytesProcessed < SourceLength
CurrentBytes = cStream.Read(Buffer, 0, 4096)
output.Write(Buffer, 0, CurrentBytes)
BytesProcessed += CLng(CurrentBytes)
PercentDone = CInt((BytesProcessed / SourceLength) * 100)
RaiseEvent Progress(PercentDone)
Loop
End Select
output.Close()
input.Close()
File.Delete(source)
RaiseEvent ReturnType(ActionReturnType.Good)
Return True
Catch ex As Exception
output.Close()
input.Close()
RaiseEvent ReturnType(ActionReturnType.Bad)
Return False
End Try
End Function