In: Computer Science
In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet.
Given an arbitrary cipher text file, you need to write a C++ program to find out the value of the shift going down the alphabet and decrypt the cipher text to plaintext. You must not hard code the cipher text nor any shift values in your program. Test your program with the sample cipher text below (only the alphabetic letters are changed):
Ty ncjaezrclasj, pyncjaetzy td esp acznpdd zq eclydqzcxtyr tyqzcxletzy (cpqpccpo ez ld awltyepie) fdtyr ly lwrzctesx (nlwwpo ntaspc) ez xlvp te fycplolmwp ez lyjzyp pinpae eszdp azddpddtyr dapntlw vyzhwporp, fdflwwj cpqpccpo ez ld l vpj. Esp cpdfwe zq esp acznpdd td pyncjaepo tyqzcxletzy (ty ncjaezrclasj, cpqpccpo ez ld ntaspcepie).
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
// Used to shift the alphabets in an character array
void shift_char_array(char array[], int shift)
{
char * arr = (char *) malloc (sizeof(array));
int i;
for(i = 0; i < strlen(arr); i++)
{
// Shift the alphabets if it is a letter or a capitalised letter
if(array[i] >= 'a' && array[i] <= 'z')
arr[i] = 'a' + (array[i] - 'a'+ shift) %26;
else if(array[i] >= 'A' && array[i] <= 'Z')
arr[i] = 'A' + (array[i] - 'A' + shift) % 26;
else
arr[i] = array[i];
}
return arr;
}
// Fuction to take input string
char * getmessage()
{
char * data = (char *) malloc(1000);
printf("Enter a String:\t");
scanf("%[^\n]s", data);
return data;
}
int main()
{
char * data = getmessage();
// Print every shifted message
for(int i = 0; i < 26; i++)
{
char * shifted_msg = shift_char_array(data, i);
printf("text with shift %d", i);
printf("%s\n", shifted_ms);
free(shifted_msg);
}
// Further more you can find all of the above words in an dictionary to determine the exact shift or select manually which of the above 26 text is right
return 0;
}