'Advanced Encryption Standard in VB.NET

I'm working on my final project in college. It is about advanced encryption standard (AES) for multimedia files (Text and image), but I need some explanation about codes that I don't understand.

 Imports System
 Imports System.Collections.Generic
 Imports System.Text

 Imports System.IO
 Imports System.Security
 Imports System.Security.Cryptography
 Imports System.Diagnostics
 Imports System.Runtime.CompilerServices

 Imports System.Drawing.Imaging

Module CryptoStuff

Public key_size_bits_ku As Integer = 128
Public iv_ku() As Byte
Private Sub MakeKeyAndIV(ByVal password As String, ByVal salt() As Byte, ByVal key_size_bits As Integer,
                         ByVal block_size_bits As Integer, ByRef key() As Byte, ByRef iv() As Byte)
    Dim derive_bytes As New Rfc2898DeriveBytes(password, salt, 1000)
    key = Encoding.ASCII.GetBytes(password)
    iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
End Sub

Region "Enkripsi file dan stream"

Public Function imgToByteArray(ByVal img As Image) As Byte()
    Using mStream As New MemoryStream()
        img.Save(mStream, img.RawFormat)
        Return mStream.ToArray()
    End Using
End Function

Public Sub EncryptFile(ByVal password As String, ByVal in_file As String,
                       ByVal out_file As String)
    CryptFile(password, in_file, out_file, True)
End Sub
Public Sub DecryptFile(ByVal password As String, ByVal in_file As String,
                       ByVal out_file As String)
    CryptFile(password, in_file, out_file, False)
End Sub
Public Sub CryptFile(ByVal password As String, ByVal in_file As String,
                     ByVal out_file As String, ByVal encrypt As Boolean)
        Using in_stream As New FileStream(in_file, FileMode.Open, FileAccess.Read)
        Using out_stream As New FileStream(out_file, FileMode.Create, FileAccess.Write)
             CryptStream(password, in_stream, out_stream, encrypt)
        End Using
    End Using
End Sub

Public Function byteArrayToImage(ByVal byteArrayIn As Byte()) As Image
    Using mStream As New MemoryStream(byteArrayIn)
        Return Image.FromStream(mStream)
    End Using
End Function

Public Sub CryptStream(ByVal password As String, ByVal in_stream As Stream,
                       ByVal out_stream As Stream, ByVal encrypt As Boolean)        
    Dim aes_provider As New AesCryptoServiceProvider()

    Dim key_size_bits As Integer = 0
    For i As Integer = 1024 To 1 Step -1
        If (aes_provider.ValidKeySize(i)) Then
            key_size_bits = i
            Exit For
        End If
    Next i
    Debug.Assert(key_size_bits > 0)
    Console.WriteLine("Key size: " & key_size_bits)

    Dim block_size_bits As Integer = aes_provider.BlockSize

    Dim key() As Byte = Nothing
    Dim iv() As Byte = Nothing
    'Dim salt() As Byte = {&H0, &H0, &H1, &H2, &H3, &H4, &H5, &H6, &HF1, &HF0, &HEE, &H21, &H22, &H45}
    'MakeKeyAndIV(password, salt, key_size_bits_ku, block_size_bits, key, iv)
    key = Encoding.ASCII.GetBytes(password)
    iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

     Dim crypto_transform As ICryptoTransform
    If (encrypt) Then
        crypto_transform = aes_provider.CreateEncryptor(key, iv)
    Else
        crypto_transform = aes_provider.CreateDecryptor(key, iv)
    End If


    Try
        Using 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
        End Using
    Catch
    End Try

    crypto_transform.Dispose()
End Sub

End Region ' Encrypt Files and Streams"

End Module

The codes that I don't understand are these:

     Dim key_size_bits As Integer = 0
     For i As Integer = 1024 To 1 Step -1
        If (aes_provider.ValidKeySize(i)) Then
            key_size_bits = i
            Exit For
        End If
     Next i
     Debug.Assert(key_size_bits > 0)
     Console.WriteLine("Key size: " & key_size_bits)

     Dim block_size_bits As Integer = aes_provider.BlockSize

Can you explain the use of these codes? Thanks before



Solution 1:[1]

This application I wrote is very effective and will encrypt whatever you want. I left notes in it to answer all your questions. At the bottom, you will see an added class to reduce memory usage of the program. It works rather well, (by 8% -10%) Enjoy. Items needed: *3 buttons (Browse) (Encrypt) (Decrypt) *1 TextBox For the project video, see my link:

Part 1: https://www.youtube.com/watch?v=sVaA2q8ttzQ

Part 2: https://www.youtube.com/watch?v=TyafeBJ53YU

'Created by: Rythorian77 | github.com/rythorian77
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class Form1


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ramClass As New AESRam()
    End Sub

    Private Sub Browse_Click(sender As Object, e As EventArgs) Handles Browse.Click

        'Allows you to access files from folders
        Dim fetchCryptDialog As New OpenFileDialog With {
            .CheckFileExists = True,
            .InitialDirectory = "C:\",
        .Multiselect = False
        }

        If fetchCryptDialog.ShowDialog = DialogResult.OK Then
            TextBox1.Text = fetchCryptDialog.FileName
        End If

    End Sub

    Private Sub Encrypt_Click(sender As Object, e As EventArgs) Handles Encrypt.Click

        'File path goes to textbox
        Dim Rythorian77 As String = TextBox1.Text

        'This password can be whater you want.
        Dim password As String = "123456789ABCDEFG!@#$%^&*()_+"

        'A data type is the characteristic of a variable that determines what kind of data it can hold.
        'Data types include those in the following table as well as user-defined types and specific types of objects.
        Dim key As Byte() = New Byte(31) {}

        'When overridden in a derived class, encodes a set of characters into a sequence of bytes.
        Encoding.Default.GetBytes(password).CopyTo(key, 0)

        'RijndaelManaged still works but is considered obsolete in todays world so we use AES
        'Represents the abstract base class from which all implementations of the Advanced Encryption Standard (AES) must inherit.
        'https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=net-6.0
        Dim aes As New RijndaelManaged() With
            {
                .Mode = CipherMode.CBC,
                .KeySize = 256,
                .BlockSize = 256,
                .Padding = PaddingMode.Zeros
            }

        'Reads a sequence of bytes from the current memory stream and advances the position within the memory stream by the number of bytes read. 
        Using mnemonicData As New MemoryStream

            'Defines a stream that links data streams to cryptographic transformations.
            Using cStream As New CryptoStream(mnemonicData, aes.CreateEncryptor(key, key), CryptoStreamMode.Write)
                Dim buffer As Byte() = File.ReadAllBytes(Rythorian77)
                cStream.Write(buffer, 0, buffer.Length)
                Dim appendBuffer As Byte() = mnemonicData.ToArray()
                Dim finalBuffer As Byte() = New Byte(appendBuffer.Length - 1) {}
                appendBuffer.CopyTo(finalBuffer, 0)
                File.WriteAllBytes(Rythorian77, finalBuffer)

            End Using
        End Using

    End Sub
 'The above code notes compliment the same
    Private Sub Decrypt_Click(sender As Object, e As EventArgs) Handles Decrypt.Click
        Dim Rythorian77 As String = TextBox1.Text

        Dim password As String = "123456789ABCDEFG!@#$%^&*()_+"

        Dim key As Byte() = New Byte(31) {}

        Encoding.Default.GetBytes(password).CopyTo(key, 0)

        Dim aes As New RijndaelManaged() With
            {
                .Mode = CipherMode.CBC,
                .KeySize = 256,
                .BlockSize = 256,
                .Padding = PaddingMode.Zeros
            }

        Using mnemonicData As New MemoryStream
            '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>    < aes.CreateDecryptor > is the only change from above aes.CreateEncryptor
            Using cStream As New CryptoStream(mnemonicData, aes.CreateDecryptor(key, key), CryptoStreamMode.Write)
                Dim buffer As Byte() = File.ReadAllBytes(Rythorian77)
                cStream.Write(buffer, 0, buffer.Length)
                Dim appendBuffer As Byte() = mnemonicData.ToArray()
                Dim finalBuffer As Byte() = New Byte(appendBuffer.Length - 1) {}
                appendBuffer.CopyTo(finalBuffer, 0)
                File.WriteAllBytes(Rythorian77, finalBuffer)

            End Using
        End Using

    End Sub

End Class



**Add this separate Class:**

Imports System.Runtime.InteropServices

Public Class AESRam

    'This controls the amount of RAM that your process uses, it doesn't otherwise have any affect on the virtual memory size of your process. 
    'Sets the minimum and maximum working set sizes for the specified process.
    'This will cut memory usage in half.
    <DllImport("KERNEL32.DLL", EntryPoint:="SetProcessWorkingSetSize", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)>
    Friend Shared Function SetProcessWorkingSetSize(pProcess As IntPtr, dwMinimumWorkingSetSize As Integer, dwMaximumWorkingSetSize As Integer) As Boolean
    End Function

    'Retrieves a pseudo handle for the current process.
    <DllImport("KERNEL32.DLL", EntryPoint:="GetCurrentProcess", SetLastError:=True, CallingConvention:=CallingConvention.StdCall)>
    Friend Shared Function GetCurrentProcess() As IntPtr
    End Function

    'See Above
    Public Sub New()
        Dim pHandle As IntPtr = GetCurrentProcess()
        SetProcessWorkingSetSize(pHandle, -1, -1)
    End Sub

End Class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1