【问题标题】:How to advance string 3 letters in the alphabet (Caesar cipher)?如何在字母表中推进字符串 3 个字母(凯撒密码)?
【发布时间】:2019-01-27 07:44:31
【问题描述】:

我正在尝试制作一个加密用户提交的字符串的程序。我想使用一种加密技术,其中字符串在字母表中是高级 3 个字母。
示例:abc 将变为 def
目前我有一个文本框 (TextBox1) 和一个按钮 (Button1)。
到目前为止我的代码:

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

问题是当我运行它时,它只输出 1 个字母。
我做错了什么?

【问题讨论】:

  • 你需要一个 for 循环来遍历每个字符来构建你的结果。
  • 另外,使用 ASCW()CHRW(),因为我们现在在 Unicode 而不是 ASCII 世界中工作。
  • XYZxyz 将变为 [ \ ]{ | } 。这是一个可行的选择吗?或者你想从A, a重新开始?
  • 无论你在做什么,它不是加密。它可能几乎没有资格作为密码。 .Net 内置了几个真正的加密算法。你应该看看其中之一。

标签: string vb.net encryption caesar-cipher


【解决方案1】:

Caesar cipher 方法。接受正向和负向偏移,以及可选的一些字母。
后者,将使用不同于通常的 US-ASCII 的 ASCII 表进行测试。

它不会改变数字(跳过),但如果需要,您可以使用相同的模式对其进行修改。

使用Scramble 参数选择打乱(真)或解乱(假)。

示例测试代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多