あなたは私のアプローチを試すことができます。
暗号化:
(コードをクリーンアップ)
''' <summary>
''' Encrypts a string using Caesar's substitution technique.
''' </summary>
''' <remarks>
''' http://en.wikipedia.org/wiki/Caesar_cipher
''' </remarks>
''' <param name="text">The text to encrypt.</param>
''' <param name="shift">The character shifting.</param>
''' <param name="charSet">The character set to use in encoding.</param>
''' <returns>The encrypted string.</returns>
Public Shared Function CaesarEncrypt(ByVal text As String,
ByVal shift As Integer,
Optional ByVal charSet As String =
"abcdefghijklmnopqrstuvwxyz" &
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" & " ") As String
Dim sb As New System.Text.StringBuilder With {.Capacity = text.Length}
For Each c As Char In text
Dim charIndex As Integer = charSet.IndexOf(c)
If charIndex = -1 Then
Throw New Exception(String.Format("Character '{0}' not found in character set '{1}'.", c, charSet))
Else
Do Until (charIndex + shift) < (charSet.Length)
charIndex -= charSet.Length
Loop
sb.Append(charSet(charIndex + shift))
End If
Next c
Return sb.ToString
End Function
復号化:
''' <summary>
''' Decrypts a string using Caesar's substitution technique.
''' </summary>
''' <remarks>
''' http://en.wikipedia.org/wiki/Caesar_cipher
''' </remarks>
''' <param name="text">The encrypted text to decrypt.</param>
''' <param name="shift">The character shifting to reverse the encryption.</param>
''' <param name="charSet">The character set to use in decoding.</param>
''' <returns>The decrypted string.</returns>
Public Shared Function CaesarDecrypt(ByVal text As String,
ByVal shift As Integer,
Optional ByVal charSet As String =
"abcdefghijklmnopqrstuvwxyz" &
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" & " ") As String
Return CaesarEncrypt(text, shift, String.Join("", charSet.Reverse))
End Function
テストの使用と結果:
Dim value As String = "Hello World"
Dim encrypted As String = CaesarEncrypt(value, shift:=15)
Dim decrypted As String = CaesarDecrypt(encrypted, shift:=15)
Debug.WriteLine(String.Format("Unmodified string: {0}", value))
Debug.WriteLine(String.Format("Encrypted string: {0}", encrypted))
Debug.WriteLine(String.Format("Decrypted string: {0}", decrypted))
変更されていない文字列: Hello World
暗号化された文字列: WtAADokDGAs
復号化された文字列: Hello World