Search code examples
vb.netvb.net-2010caesar-cipher

VB - Caesar Cipher emulation


I'm trying to emulate Caesar Cipher encryption. The problem is whenever I input "wxyz"
(shifted by 3) the output is "z{|}". But the expected output should be "zabc".

Anyone knows what to add?

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim plaintext As String = TextBox1.Text
            Dim charArray() As Char = plaintext.ToCharArray
            Dim shift = TextBox2.Text
            Dim character As String
            Dim temp As String
            TextBox3.Text = ""



            If shift <> "" And IsNumeric(shift) Then
                If plaintext = "" Then
                    MsgBox("Please input some plain text")
                    Exit Sub
                End If
                If shift > 26 Then
                    MsgBox("Maximum shifts reached. Limit is 26!!")
                    Exit Sub
                End If
                For loope = 0 To charArray.Length - 1 Step +1
                    temp = charArray(loope)

                    character = Chr(Asc(temp) + shift)

                    TextBox3.Text += character


                Next
                Exit Sub
            Else
                MsgBox("Input numbers only!!")
            End If


        End Sub

Solution

  • When you shift an Ascii code you should verify that it does not get greater than 122, which is the Ascii code for the character "z". If you go beyond that point, you will get punctuation marks, symbols and that stuff. Google "ASCII table" and you can easily see it for yourself.

    So, to solve your problem, if the Ascii code you get after shifting is greater than 122 you should go back and begin by 97 again, which is the ascii for "a".

    So, instead of this:

                For loope = 0 To charArray.Length - 1 Step +1
                    temp = charArray(loope)
                    character = Chr(Asc(temp) + shift)
                    TextBox3.Text += character
                Next
    

    You should do something like

                For loope = 0 To charArray.Length - 1 Step +1
                    temp = charArray(loope)
                    character = Chr(Asc(temp) + shift)
                    ' You substract 26, the whole length of the alphabet
                    If character > 122 Then
                       character = character - 26 
                    End If
                    TextBox3.Text += character
                Next
    

    No quite sure that this would be stable if shift is greater than 26, but anyhow you already check its value so it should work.