Resolved AES Decyption

zackmark29

Active member
Joined
Apr 21, 2020
Messages
28
Programming Experience
Beginner
Could someone help me.
I found this code from somewhere but I don't know how I can use this in my input files
I want to have the output file
I really don't know much how to use function.


VB.NET:
 Class Decrypter
        Public Shared Function AES128Decrypt(ByVal filePath As String, ByVal keyByte As Byte(), ByVal ivByte As Byte(), ByVal Optional mode As CipherMode = CipherMode.CBC) As Byte()
            Dim fs As FileStream = New FileStream(filePath, FileMode.Open)
            Dim size As Long = fs.Length
            Dim inBuff As Byte() = New Byte(size - 1) {}
            fs.Read(inBuff, 0, inBuff.Length)
            fs.Close()
            Dim dcpt As Aes = Aes.Create("AES")
            dcpt.BlockSize = 128
            dcpt.KeySize = 128
            dcpt.Key = keyByte
            dcpt.IV = ivByte
            dcpt.Mode = mode
            dcpt.Padding = PaddingMode.PKCS7
            Dim cTransform As ICryptoTransform = dcpt.CreateDecryptor()
            Dim resultArray As Byte() = cTransform.TransformFinalBlock(inBuff, 0, inBuff.Length)
            Return resultArray
end function
        End Function
 
Do you understand how encryption works in .NET? If not, that should be your first task. Copying code off the web with no understanding of what that code does is rarely a good idea. That method fairly obviously takes the path of an encrypted file and returns the decrypted data as a Byte array. If you don't know what the parameters mean then you should learn a bit about AES encryption and how it's implemented in .NET.
 
Do you understand how encryption works in .NET? If not, that should be your first task. Copying code off the web with no understanding of what that code does is rarely a good idea. That method fairly obviously takes the path of an encrypted file and returns the decrypted data as a Byte array. If you don't know what the parameters mean then you should learn a bit about AES encryption and how it's implemented in .NET.

I know a little about AES but without using function.
I just can't really understand how function works. although it's obviously I can see the path and input. But I'm still learning how to implement it in my main code.
 
The reason why I want to know how it's works. because I want to clean and separate my ugly codes like this.

VB.NET:
outputPath = Path.Combine(txtOutputPath.Text, txtOutputFilename.Text & ".ts")
        Dim newWorker As BackgroundWorker = DirectCast(sender, BackgroundWorker)

        Dim IV(15) As Byte
        Dim KEY As Byte() = File.ReadAllBytes(txtKeyPath.Text)
        Dim counter As Double = 1

        If File.Exists(outputPath) Then
            Dim d As DialogResult = MessageBox.Show("The file '" & outputPath & "' already exists. Do you want to overwrite??", "Overwrite existing file?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If d = DialogResult.No Then
                fileExists = True
                Return
            End If
        End If

        If Not Directory.Exists(txtOutputPath.Text) Then
            Directory.CreateDirectory(txtOutputPath.Text)
        End If

        Try
            decrypting = True
            Using outputFs = New FileStream(outputPath, FileMode.Create, FileAccess.Write)
                For Each i As Object In LV.Items
                    sourceItems = CType(i, SourceItem)
                    Dim inputFiles As String = sourceItems.Filename
                    Dim countFiles As Long = LV.Items.Count
                    Using inputFs = New FileStream(inputFiles, FileMode.Open, FileAccess.Read, FileShare.Read)

                        Using AES As New AesManaged
                            AES.BlockSize = 128
                            AES.FeedbackSize = 128
                            AES.Key = KEY
                            AES.IV = IV
                            AES.Mode = CipherMode.CBC
                            AES.Padding = PaddingMode.PKCS7

                            Using decryptor As ICryptoTransform = AES.CreateDecryptor
                                Using cryptoSR = New CryptoStream(inputFs, decryptor, CryptoStreamMode.Read)
                                    While inputFs.Position < countFiles

                                        newWorker.ReportProgress(counter / countFiles * 100)

                                        cryptoSR.CopyTo(outputFs)
                                        mReset.WaitOne()

                                        If tryAbort Then
                                            ss.Text = "Aborting process..."
                                            ss.ForeColor = Color.IndianRed
                                            mReset.Reset() 'pause the process
                                            Dim r = MessageBox.Show("Do you to abort the process?", "Decypting in progress", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                                            If r = DialogResult.No Then
                                                ss.Text = "Resuming"
                                                ss.ForeColor = Color.DarkGreen
                                                tryAbort = False
                                                mReset.Set() 'resume the process
                                            ElseIf r = DialogResult.Yes Then
                                                If bgw.IsBusy Then
                                                    bgw.CancelAsync()
                                                    bgw.Dispose()
                                                    If bgw.CancellationPending = True Then
                                                        e.Cancel = True
                                                        Exit For
                                                    End If
                                                End If
                                                decrypting = False
                                                Return
                                            End If
                                        End If
                                        counter += 1
                                    End While
                                    If inputFs Is Nothing Then
                                        inputFs.Close()
                                        inputFs.Dispose()
                                    End If
                                End Using
                            End Using
                        End Using
                    End Using
                Next
                If outputFs Is Nothing Then
                    outputFs.Close()
                    outputFs.Dispose()
                End If
            End Using
        Catch ex As Exception
            MsgBox(ex.Message, vbCritical, "Error")
        End Try
        AutoDeleteSourceFiles()
        AutoOpenOutputFolder()
        AutoClearItems()
        decrypting = False
 
I know a little about AES but without using function.
It's the same code either way. A function is simply a way of making a chunk of code reusable. You identify the variables and extract those as method parameters and the rest of the code remains the same. This is true of any code, not just decryption code. Either you know how encryption/decryption works or you don't. Where the code is located is not relevant to that.

If what you actually want is to refactor your own code then that's what you should do. You can read up on general refactoring and optimisation techniques and apply them to any code. You can break your code down into units of functionality and then break each unit out into its own method. You might, for instance, determine that one unit is made up purely of two other units. In that case you would extract out the two inner units into their own methods and then the outer unit into its own method that did nothing but call the other two.

Instead of trying to tackle each situation in isolation, you should try to learn principles that you can apply to a number of similar but different situations. Then you won't have to reinvent the wheel every time.
 
Back
Top