Caesar Cipher C# - 如何正确解密

Caesar Cipher C# - How to decrypt correctly

当我输入一个带有 'a' 的字符串时,我使用 -1 作为 returns 符号的移位。我该如何修复解密。

using System;

namespace CaesarCipher1
{
    class Program
    {
        static string Encrypt(string value, int shift)
        {
            char[] buffer = value.ToCharArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                char letter = buffer[i];
                letter = (char)(letter + shift);
                if (letter > 'z')
                {
                    letter = (char)(letter - 26);
                }
                else if (letter < 'a')
                {
                    letter = (char)(letter + 26);
                }
                // Store.
                buffer[i] = letter;
            }
            return new string(buffer);
        }
        static string Decrypt(string value, int shift)
        {
            return Encrypt(value, 26 - shift);
        }


        static void Main(string[] args)
        {
            bool Continue = true;

            Console.WriteLine("      Ceasar Cipher");
            Console.WriteLine("-------------------------\n");

            while (Continue)
            {
                try
                {
                    Console.WriteLine("\nType a string to encrypt:");
                    string UserString = Console.ReadLine();

                    Console.Write("\nShift: ");
                    int key = Convert.ToInt32(Console.ReadLine());

                    Console.WriteLine("\nEncrypted Data: ");

                    string cipherText = Encrypt(UserString, key);
                    Console.WriteLine(cipherText);
                    Console.Write("\n");

                    Console.WriteLine("Decrypted Data:");

                    string t = Decrypt(cipherText, key);
                    Console.WriteLine(t);

                    Console.WriteLine("\nDo you want to continue?");
                    Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
                    string response = Console.ReadLine();
                    Continue = (response == "Yes");

                }
                catch (FormatException ex)
                {
                    Console.WriteLine("You entered a bad operation, try another one");
                }
            }

        }
    }
}

凯撒密码

输入要加密的字符串: 行动

班次:-1

加密数据: zbs

解密数据: {ct

你想继续吗? 输入 Yes 继续或按任何其他键,然后按 enter 退出: 是

输入要加密的字符串: 行动

班次:1

加密数据: bdu

解密数据: 行动

由于您使用 letter = (char)(letter - 26); 之类的代码纠正超出范围的字母的方式,您必须采取一些措施来确保您的班次不会太大。 } 我会将此行添加到 Encrypt 函数的开头。

shift %= 26;

这将确保您的班次永远不会超过 26。

static string Encrypt(string value, int shift)
{
    shift %= 26; // add this line
    char[] buffer = value.ToCharArray();
    for (int i = 0; i < buffer.Length; i++)

    // ...