-1

Currently I am trying to make a brute force caesar cipher in C++ which shows all the iterations as it guesses each key.

Here is my code thus far:

#include <iostream>

using namespace std;

int main()
{
    char message[100], ch;
    int i;

    cout << "Enter a message to decrypt: ";
    cin.getline(message, 100);

    for(int key = 0; key<26 ; key++)
    {
        for(i = 0; message[i] != '\0'; ++i){
            ch = message[i];

            if(ch >= 'a' && ch <= 'z'){
                ch = ch - key;

                if(ch < 'a'){
                    ch = ch + 'z' - 'a' + 1;
                }

                message[i] = ch;
            }
            else if(ch >= 'A' && ch <= 'Z'){
                ch = ch - key;

                if(ch > 'a'){
                    ch = ch + 'Z' - 'A' + 1;
                }

                message[i] = ch;
            }
        }
        cout << "Decrypted message: " << message << " " << endl ;
    }

    return 0;
}

The problem I have is when it is showing the guesses, it seems to skip letters when they are lowercase and just gets stuck when they are uppercase and repeats the same string. In the example the code is LT HDGJWJFLQJX which should decrypt to GO CYBEREAGLES. Both the uppercase and lowercase program outputs are shown in the images attached.

Image 1

Image 2

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Toror
  • 1
  • 1
  • You first need to reformat your code. It is not lining up correctly. – Alain Mar 15 '17 at 01:54
  • Your image of text [isn't very helpful](//meta.unix.stackexchange.com/q/4086). It can't be read aloud or copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please [edit] your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors). – Toby Speight Mar 15 '17 at 14:53

1 Answers1

-1

You're decrypting message in place, so when you make your second guess, you're decrypting the result of the first decryption. The 3rd guess is working with the result of the second decryption, etc.

When you write out the decrypted guess, it should go into a different array than message, so that the next iteration can start with the original encryption data.

Edit: Create another array, char decrypted[100];, then write you decrypted characters into it (decrypted[i] = ch;). Don't forget the nul (zero) character at the end.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • @1201ProgramAlarm Okay great, thank you for your answer!! But whenever I enter the message, it will stop decrypting once there is a space in the message, how would I go about fixing that? – Toror Mar 16 '17 at 02:23
  • @Toror Run it in a debugger to see what the problem is. – 1201ProgramAlarm Mar 16 '17 at 05:17