user1548346 user1548346 - 29 days ago 15
C Question

Ceaser Cipher crack using C language

I am writing a program to decrypt text using ceaser cypher algorithm.
till now my code is working fine and gets all possible decrypted results but I have to show just the correct one, how can I do this?
below is the code to get all decrypted strings.
for my code answer should be "3 hello world".

void main(void)
{
char input[] = "gourz#roohk";
for(int key = 1;x<26;key++)
{
printf("%i",input[I]-x%26);
for(int i = strlen(input)-1;i>=0;i--)
{
printf("%c",input[I]-x%26);
}
}
}

Answer

Recall that a Caesar Cipher has only 25 possible shifts. Also, for text of non-trivial length, it's highly likely that only one shift will make the input make sense. One possible approach, then, is to see if the result of the shift makes sense; if it does, then it's probably the correct shift (e.g. compare words against a dictionary to see if they're "real" words; not sure if you've done web services yet, but there are free dictionary APIs available). Consider the following text: 3 uryyb jbeyq. Some shifts of this:

  • 3 gdkkn vnqkc (12)
  • 3 xubbe mehbt (3)
  • 3 hello world (13)
  • 3 jgnnq yqtnf (15)
  • Etc.

As you can see, only the shift of 13 makes this text contain "real" words, so the correct shift is probably 13.

Another possible solution (albeit more complicated) is through frequency analysis (i.e. see if the resulting text has the same - or similar - statistical characteristics as English). For example, in English the most frequent letter is "e," so the correct shift will likely have "e" as the most frequent letter. The key word here is "likely" - it's not statistically certain and it's possible for text to avoid detection in that way.