0

I am doing a Caesar's cipher assignment where you have to encrypt and decrypt a word with a +5 letter key. I am struggling making the Decrypt function work as I get an exception that the index is out of range. I know that there is something wrong with what is getting passed into the function as it does not seem to register the previous moves of the encryptor so when I try to decrypt it through the letterPosition - 5 to revert it back from the letterPosition + 5 it does not seem to understand and puts the index out of range. Thanks

{
    public class Cipher
    {
        public Cipher(){}
        char[] encryptedMessage;
        string encodedString;
        string input;

        public void method()
        {
            char[] alphabet = new char[] {'a','b','c','d','e','f','g'
            ,'h','i','j','k','l','m','n','o','p','q','r','s','t','u'
            ,'v','w','x','y','z'};
            Console.WriteLine("Enter you secret phrase");
            input = Console.ReadLine();
            char[] secretMessage = input.ToCharArray();
            char[] encryptedMessage = new char[secretMessage.Length];
            for (int i = 0; i < secretMessage.Length; i++)
            {
                char letter = secretMessage[i];
                int letterPosition = Array.IndexOf(alphabet, letter);
                int newLetterPosition = (letterPosition + 5) % 26;
                char letterEncoded = alphabet[newLetterPosition];
                encryptedMessage[i] = letterEncoded;
            }
            encodedString = String.Join(" ", encryptedMessage);
            Console.WriteLine($"Your encoded message is {encodedString}");
            Console.WriteLine($"The decoded message is {input}");
        }
        public void Decrypt()
        {
            
            for (int i = 0; i < secretMessage.Length; i++)
            {
                char letter = secretMessage[i];
                int letterPosition = Array.IndexOf(alphabet, letter);
                int newLetterPosition = (letterPosition - 5) % 26;
                char letterEncoded = alphabet[newLetterPosition];
                encryptedMessage[i] = letterEncoded;
            }
            encodedString = String.Join(" ", encryptedMessage);
            Console.WriteLine($"Your encoded message is {encodedString}");
            Console.WriteLine($"The decoded message is {input}");
        }


    }
}

1 Answers1

2

Instead of moving 5 letters back, move 21 letters ahead and use the modulo 26 operation then during decrypt.

int newLetterPosition = (letterPosition + 21) % 26;
NineBerry
  • 26,306
  • 3
  • 62
  • 93