Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Develop a Visual Basic Windows Forms application that will ‘encrypt’ (character

ID: 3669150 • Letter: D

Question

Develop a Visual Basic Windows Forms application that will ‘encrypt’ (character shift)’ the characters in a string based on a symmetric key (process known as symmetric-key cryptography). The application must also ‘decrypt’ the message based on the symmetric key used. General Requirements The clear-text message (that will be ‘encrypted’) is stored in a text-file. The text-file is to be selected using an OpenFileDialog Windows control object Text-file contents are to be displayed in a Textbox control located on the Windows form (you can also use this textbox to input clear-text characters) Keys are contained in a ComboBox control object. Users can select a particular key resulting in alternate cipher-text outputKeys are to be a minimum of 5 digits. Each key digit is used for encoding where your program will move to the next digit for every character in the clear-text message. Since there are a limited number of digits in a key, your program must ‘wrap-back’ to the first digit The selected key must be stored in an array The resulting cipher-text output is to be stored in a text file and displayed in a textbox control on the Windows form Using the same key for encryption, decrypt the cipher-text message and display it in a label on the Windows Form Since only printable characters are used (see table), if the ASCII code becomes larger than 126, you will need to wrap around to the ASCII code 32 (space) Use exception handling where needed…for example, FileNotFound or DirectoryNotFound. Example: Using a sample key of 58912, the output would be as follows: Clear Character N J I T V B N e T ASCII Code 78 74 73 84 32 86 66 78 101 84 ASCII Code + Key Value 83 82 82 85 34 91 74 87 102 86 Shifted Character S R R U “ [ J W f V Clear-Text: “NJIT VBNet” Cipher-Text: “SRRU”[JWfV”

Explanation / Answer

Hi Below i have written a code that will your own encryption and decryption program using VB.NET

Import the following namespaces:

'Cryptography NameSpace

Imports System.Security.Cryptography

'For File Input & Output

Imports System.IO

Declare the following variables in General Declarations:

'Original TextBox Text

Private OrigText As String

'New Text Entered

Private NewText As String

'Contents Have Changed

Private FileTextChanged As Boolean

'File Name To Open

Private strFileName As String

Sub Procedures and Functions:

''' Creates The Encrypted File, With The Specified Password ''' On The Speciffied File ''' ''' Gets The Encrypted File And Loads ''' Contents If Correct Details Were Supplied ''' ''' Converts Normal Text To Hexadecimal ''' ''' Convert Normal Characters To Byte Objects ''' ''' Convert Hexadecimal To Normal Text '''

'''

'''

'''

'''

'''

Private Sub ApplyCrypt(ByVal strInFileName As String, ByVal strOutFileName As String, _

ByVal strPassword As String)

'If TextBox Text Changed

If FileTextChanged Then

'Create Password Key

Dim TestValueBytes As Byte() = _

System.Text.Encoding.ASCII.GetBytes("This Is A Test")

Dim PassKey As Rfc2898DeriveBytes = New _

Rfc2898DeriveBytes(strPassword, TestValueBytes)

'Create Algorithm And Specify The Key And Pass

Dim rmAlgo As RijndaelManaged = New RijndaelManaged

rmAlgo.Key = PassKey.GetBytes(rmAlgo.KeySize / 8)

rmAlgo.IV = PassKey.GetBytes(rmAlgo.BlockSize / 8)

'Read Unencrypted File

Dim strSourceFile As FileStream = _

New FileStream(strInFileName, FileMode.Open, FileAccess.Read)

'Store Its Data

Dim strData(strSourceFile.Length) As Byte

strSourceFile.Read(strData, 0, CType(strSourceFile.Length, Integer))

'Create ICryptoTransform And CryptoStream Objects

Dim ictEncryptor As ICryptoTransform = rmAlgo.CreateEncryptor

'Get Output File

Dim strDestFile As FileStream = New _

FileStream(strOutFileName, FileMode.OpenOrCreate, FileAccess.Write)

'Write The Encryption

Dim csEncryptStream As CryptoStream = _

New CryptoStream(strDestFile, ictEncryptor, CryptoStreamMode.Write)

csEncryptStream.Write(strData, 0, strData.Length)

'Close All File Handles

csEncryptStream.Close()

strSourceFile.Close()

strDestFile.Close()

End If

End Sub

'''

'''

'''

'''

'''

Private Sub LoadCrypt(ByVal strInFileName As String, ByVal strOutFileName As String, _

ByVal strPassword As String)

Try

'Create Password Key

Dim TestValueBytes As Byte() = _

System.Text.Encoding.ASCII.GetBytes("This Is A Test")

Dim PassKey As Rfc2898DeriveBytes = New _

Rfc2898DeriveBytes(strPassword, TestValueBytes)

'Create Algorithm And Specify The Key And Pass

Dim rmAlgo As RijndaelManaged = New RijndaelManaged

rmAlgo.Key = PassKey.GetBytes(rmAlgo.KeySize / 8)

rmAlgo.IV = PassKey.GetBytes(rmAlgo.BlockSize / 8)

Dim ictDecryptor As ICryptoTransform = rmAlgo.CreateDecryptor

'Read Encrypted File

Dim strSourceFile As FileStream = _

New FileStream(strInFileName, FileMode.Open, FileAccess.Read)

'Load Encryption

Dim csDecryptStream As CryptoStream = _

New CryptoStream(strSourceFile, ictDecryptor, CryptoStreamMode.Read)

'Store Its Data

Dim fileData(strSourceFile.Length) As Byte

csDecryptStream.Read(fileData, 0, CType(strSourceFile.Length, Integer))

'Get Destination File

Dim strDestFile As FileStream = New FileStream(strOutFileName, _

FileMode.OpenOrCreate, FileAccess.Write)

'Write To destination File

strDestFile.Write(fileData, 0, fileData.Length)

'Close All File Handles

csDecryptStream.Close()

strSourceFile.Close()

strDestFile.Close()

'Load File Into TextBox

txtCrypto.Text = File.ReadAllText(strOutFileName)

txtCrypto.SelectionLength = 0

txtCrypto.SelectionStart = 0

'Detect Changes To Original Text

OrigText = txtCrypto.Text

NewText = txtCrypto.Text

FileTextChanged = False

'Wrong Password Supplied

Catch ex As Exception

MessageBox.Show("Wrong Password And / Or FileName Entered", "Crypto", _

MessageBoxButtons.OK, MessageBoxIcon.Stop)

End Try

End Sub

'''

'''

'''

'''

Public Function ToHexStr(ByVal strNormal As String) As String

'Get Text To Convert

Dim arrBytes As Integer() = ConvertCharsToBytes(strNormal)

'Creates New StringBuilder Object

Dim sbHexBuilder As System.Text.StringBuilder = New System.Text.StringBuilder

'Loop Through Characters

'And Convert To Hex

For i As Integer = 0 To arrBytes.Length - 1

sbHexBuilder.Append(String.Format("{0:x2}", Hex(arrBytes(i))))

Next

'Return Hex String

Return sbHexBuilder.ToString()

End Function

'''

'''

'''

'''

Private Function ConvertCharsToBytes(ByVal strInput As String) As Integer()

'Convert Each Normal Character To a Char Object

Dim c As Char() = strInput.ToCharArray()

'Create A Byte Array

Dim arrBytes As Integer()

'Store Character's Bytes Into Array

ReDim arrBytes(c.Length() - 1)

For i As Integer = 0 To c.Length() - 1

arrBytes(i) = System.Convert.ToByte(c(i))

Next

'Return Byte Object

Return arrBytes

End Function

'''

'''

'''

'''

Private Function HexToStr(ByVal HexStr As String) As String

'Create Objects

Dim strCurrentChar As String

Dim strASCII As Integer

Dim strOutput As String

'Loop Through Each Character

Do While Len(HexStr) > 0

'Get The Next Hex Number

strCurrentChar = HexStr.Substring(0, 2)

'Store It

HexStr = HexStr.Substring(2)

'Convert To Decimal

strASCII = CInt(Val("&H" & strCurrentChar))

'Convert To Normal Character

strOutput &= Chr(strASCII)

Loop

'Return Decoded String

Return strOutput

End Function

Add the following Form events:

Private Sub frmCryptoViewer_FormClosing(ByVal sender As Object, ByVal e _

As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

'If Output.txt Exists Delete It

If File.Exists("Output.txt") Then File.Delete("Output.txt")

End Sub

Private Sub frmCryptoViewer_Load(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles MyBase.Load

btnSave.Enabled = False 'Disable Save

End Sub

Add the following code for the btnLoadFile button:

Private Sub btnLoadFile_Click(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles btnLoadFile.Click

If ofdCrypt.ShowDialog = Windows.Forms.DialogResult.OK Then

'Get FileName Entered

strFileName = ofdCrypt.FileName

strFileName = ToHexStr(strFileName) 'Convert To Hex

Dim frmCryptoPass As New frmPass

If frmCryptoPass.ShowDialog = Windows.Forms.DialogResult.OK Then

'If Correct Password Supplied Load File

LoadCrypt("Encrypted.enc", "Output.txt", frmCryptoPass.CryptoPass)

End If

End If

End Sub

Add the following code for btnCopy:

Private Sub btnCopy_Click(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles btnCopy.Click

Clipboard.SetText(txtCrypto.SelectedText) 'Copy Selected Text

End Sub

btnSave should look like the following:

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles btnSave.Click

'Save To Output.txt

File.WriteAllText("Output.txt", txtCrypto.Text)

Dim frmCryptoPass As New frmPass 'Launch Password Box

If frmCryptoPass.ShowDialog = Windows.Forms.DialogResult.OK Then

'Set Password For File

ApplyCrypt("Output.txt", "Encrypted.enc", frmCryptoPass.CryptoPass)

End If

End Sub

btnExit:

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles btnExit.Click

Me.Close() 'Exit

End Sub

Last but not least,ad the folowing event for txtCrypto:

Private Sub txtCrypto_LostFocus(ByVal sender As Object, ByVal e _

As System.EventArgs) Handles txtCrypto.LostFocus

'Determine TextBox Text Change

If Not String.Compare(OrigText, NewText) Then

FileTextChanged = True

End If

End Sub

Private Sub txtCrypto_TextChanged(ByVal sender As Object, ByVal e _

As System.EventArgs) Handles txtCrypto.TextChanged

'Determine TextBox Text Change

If Not String.Compare(OrigText, NewText) Then

'If Text Changed We Can Save

btnSave.Enabled = True

End If

End Sub

frmPass

Declare the following variables:

Public CryptoPass As String 'Holds Password

Add the following Form events:

Private Sub frmPass_Load(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles MyBase.Load

Dim btnAscii As Button 'Declare New Button Object

Dim btnAsciiLeft As Integer = 10 'New Button's Left

Dim btnAsciiTop As Integer = 10 'New Button's Top

'Create Buttons Ranging From "Space" To "~"

'This Would Allow Us To Work All Keyboard Buttons

For i As Integer = Asc(" ") To Asc("~")

btnAscii = New Button 'Initialise

With btnAscii 'Set Properties

.Name = "btn_" & Chr(i) 'Set Name

.Text = Chr(i) 'Set Text

.Size = New Size(25, 25) 'Set Size

'Set Pos

.Location = New Point(btnAsciiLeft, btnAsciiTop)

.Tag = Chr(i) 'Set Tag

'Shift Buttons To The Right

btnAsciiLeft = btnAsciiLeft + 30

If Chr(i) = "0" Then 'If At 0 Start New Line

btnAsciiTop = btnAsciiTop + 50

btnAsciiLeft = 10

End If

If Chr(i) = "A" Then 'If At A Start New Line

btnAsciiTop = btnAsciiTop + 50

btnAsciiLeft = 10

End If

If Chr(i) = "R" Then 'If At R Start New Line

btnAsciiTop = btnAsciiTop + 50

btnAsciiLeft = 10

End If

If Chr(i) = "c" Then 'If At c Start At New Line

btnAsciiTop = btnAsciiTop + 50

btnAsciiLeft = 10

End If

If Chr(i) = "t" Then 'If At t Start New Line

btnAsciiTop = btnAsciiTop + 50

btnAsciiLeft = 10

End If

'If At u Shift Buttons To The Right

If Chr(i) = "u" Then

btnAsciiLeft = btnAsciiLeft + 105

btnAsciiTop = btnAsciiTop

End If

'If At } Shift Last Button To The Right

If Chr(i) = "}" Then

btnAsciiLeft = btnAsciiLeft + 105

btnAsciiTop = btnAsciiTop

End If

.Visible = True 'Make Visible

End With

Me.Controls.Add(btnAscii) 'Add To Form

'Create Event

AddHandler btnAscii.Click, AddressOf btnAscii_click

Next

End Sub

Add the btnAscii event like this:

Private Sub btnAscii_click(ByVal sender As System.Object, ByVal e _

As System.EventArgs)

'Store Clicked Button(s) In String Variable

CryptoPass = (DirectCast(sender, Button).Text)

End Sub

btnDone:

Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e _

As System.EventArgs) Handles btnDone.Click

Me.Dispose() 'Dispose This Form

End Sub

Implementation

When this program is run, frmCryptoViewer will be displayed and waiting for input. You can enter all your sensitive information in here, it can be a username and password, it can be a love letter, it doesn't matter :). Once all text has been input, you should save the document. After you have clicked the Save button, your frmPass will show, and will look like Figure 3. Here, you should click in your password. Now, what's happening in the background?

A normal Textfile named Output.txt gets created. The ApplyCrypt method then reads this document and applies the Rijndael encryption onto it, and now, creates the Encrypted.enc, and when the program exits, it deletes theOutput.txt file.

On the program's second run ( or anytime after the Encrypted.enc file has been created ), you should load the file by clicking on the Load File button. Here you should select the name of the encrypted file you've saved - in our case, Encrypted.enc, as shown in Figure 4.

The Password box displays again, and only if you have clicked in the correct password, it will load the file, If you've clicked in the wrong password, you will be notified as wrong password.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote