A 凯撒密码 https://en.wikipedia.org/wiki/Caesar_cipher方法。接受正移和负移以及可选的多个字母。
后者将使用与通常的 US-ASCII 不同的 ASCII 表进行测试。
它不会改变数字(已跳过)但如果需要,您可以使用相同的模式对其进行修改。
Use the Scramble
参数来选择加扰 (True) 或取消加扰 (False)。
示例测试代码:
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