Visual Basic Shift Cipher

时间:2014-09-29 19:01:22

标签: vb.net encryption modulo shift

我的Ceasar移位密码程序存在问题。当我必须用n个移位密码加密一些文本时,代码工作正常。但是当我想要解密一些文本时,数组索引变为负数并且我得到一个错误:发生了一个未处理的类型'System.IndexOutOfRangeException'的异常。

Public Class Form1
Dim alfabet() As Char = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "æ", "ø", "å"}


Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
    Me.Close()
End Sub



Private Sub btnKod_Click(sender As Object, e As EventArgs) Handles btnKod.Click

    Kod(txtDekodet.Text, txtTrylletal.Text, True)

End Sub


Private Sub btnDekod_Click(sender As Object, e As EventArgs) Handles btnDekod.Click

    Kod(txtKodet.Text, -txtTrylletal.Text, False)

End Sub

Function Kod(tekst As String, trylletal As Integer, skalKodes As Boolean)
    Dim nyeCharVaerdier(tekst.Length) As Char

    For i As Integer = 0 To tekst.Length - 1
        Dim nytTal As Integer = findIndex(tekst(i), trylletal)

        If nytTal = -1 Then
            nyeCharVaerdier(i) = tekst(i)

        Else
            nyeCharVaerdier(i) = alfabet(nytTal)
        End If

    Next
    If skalKodes = True Then
        txtKodet.Text = nyeCharVaerdier
    Else
        txtDekodet.Text = nyeCharVaerdier
    End If
    Return Nothing
End Function


Function findIndex(tegn As Char, trylletal As Integer) As Integer
    For alfabetTaeller As Integer = 0 To alfabet.Length - 1
        If tegn = alfabet(alfabetTaeller) Then
            Dim nytIndex As Integer = (alfabetTaeller + trylletal) Mod alfabet.Length
            Return nytIndex

        End If
    Next
    Return -1
End Function


End Class

3 个答案:

答案 0 :(得分:1)

你的子程序有效。但是,您作为查找表使用的数组被声明为char,但您尝试用字符串填充它。如果你打开了Option Strict,你会看到每个字符串下面都有一条波浪线,表示有错误。收盘后放c"对于每个角色,你的子程序都可以工作。

Dim alfabet() As Char = {"a"c, "b"c, "c"c, "d"c, "e"c, "f"c, "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, "y"c, "z"c, "æ"c, "ø"c, "å"c}

旁注。如果您不打算返回任何有意义的数据,请将例程声明为Sub而不是Function。如果要返回数据,请使用As子句指示将返回的数据类型。

答案 1 :(得分:0)

导致该错误的一件事是当数组索引太大或小于零时。尝试在Visual Studio中运行该程序。当它收到错误时,在它停止的代码行中显示所有变量的值。 (使用调试菜单)。你应该看到问题。

答案 2 :(得分:0)

我想通知如果我将alfabet()数组的长度添加到负数的新索引 - 一切正常: - )

if nytTal < 0 Then
nytTal += nytTal + alfabet.Length
End If