How to advance string 3 letters in the alphabet (Caesar cipher)?

有些话、适合烂在心里 提交于 2019-12-11 04:25:54

问题


I'm trying to make a program that encrypts a string the user submits. I want to use an encryption technique where the string is advanced 3 letters in the alphabet.
Example: abc would become def.
Currently I have a TextBox (TextBox1) and a Button (Button1).
My code so far:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim rawText As String
    rawText = TextBox1.Text
    Dim letterTxt As String = Chr(Asc(rawText) + 3)
    MsgBox(letterTxt)

End Sub

The problem is that when I run it, it only outputs 1 letter.
What did I do wrong?


回答1:


A Caesar cipher method. Accepts positive and negative shifts and, optionally, a number of alphabet letters.
The latter, to be tested with ASCII tables different than the usual US-ASCII.

It doesn't alter digits (skipped) but you can modify it using the same pattern, if needed.

Use the Scramble parameter to select scramble (True) or unscramble (False).

Sample test code:

Dim Scrambled1 As String = CaesarCipher("ABCXYZabcxyz", 3, True)
Dim Scrambled2 As String = CaesarCipher("ABCXYZabcxyz", -5, True)

'Scrambled1 is now DEFABCdefabc
'Scrambled2 is now VWXSTUvwxstu

Dim Unscrambled As String = CaesarCipher(Scrambled2, -5, false)

'Unscrambled is now ABCXYZabcxyz

Function CaesarCipher(Input As String, CaesarShift As Integer, Scramble As Boolean, Optional AlphabetLetters As Integer = 26) As String

    Dim CharValue As Integer
    Dim MinValue As Integer = AscW("A"c)
    Dim MaxValue As Integer = AscW("Z"c)
    Dim ScrambleMode As Integer = If((Scramble), 1, -1)
    Dim output As StringBuilder = New StringBuilder(Input.Length)

    If Math.Abs(CaesarShift) >= AlphabetLetters Then
        CaesarShift = (AlphabetLetters * Math.Sign(CaesarShift)) - Math.Sign(CaesarShift)
    End If

    For Each c As Char In Input
        CharValue = AscW(c)
        If Not Char.IsNumber(c) Then
            CharValue = CharValue + (CaesarShift * ScrambleMode) Mod AlphabetLetters
            CharValue = If(AscW(Char.ToUpper(c)) + (CaesarShift * ScrambleMode) > MaxValue, CharValue - AlphabetLetters, CharValue)
            CharValue = If(AscW(Char.ToUpper(c)) + (CaesarShift * ScrambleMode) < MinValue, CharValue + AlphabetLetters, CharValue)
        End If
        output.Append(ChrW(CharValue))
    Next
    Return output.ToString()
End Function


来源:https://stackoverflow.com/questions/53318544/how-to-advance-string-3-letters-in-the-alphabet-caesar-cipher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!