Caesar Says hello world!

Few months back there was a problem set on Caesar cipher and it struck to me to write this one for the readers who are interested to learn about Caesar cipher. 


Let's get started, in Caesar cipher we have predefined mapping of the 26 English alphabets with numbers from 0-25. Letter A corresponds to 0, letter B corresponds to 1, C corresponds to 2 and so on till Z corresponds to 25.


Mathematically, 


Cipher text, C = (P+K) % 26. Where P is the plain text and K is key between 1 to 25. We cannot use K=0 as it will give back the same letters as plain text.


Plain text, P = (C-K) % 26. Where C is the cipher text obtained after encryption.


That was the vanilla Caesar cipher, now what about writing "hello world!" in Caesar Cipher. The task seems simple however note that the vanilla Caesar cipher does not have mapping for space and exclamation mark (!) symbols. Let us design our own mapping similar to that of vanilla mapping with these two symbols. We add ! and space characters at the end of the mapping, with ! = 26 and space = 27.


So, finally Cipher text becomes C = (P+K) % 28 and Plain text, P = (C-K) % 28. If you execute below c code will be find output as "mjqqte twqid".


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
#include<string.h>
void encrypt();
int main()
{
 encrypt();
 return 0;
}

void encrypt()
{
 int key=5; //set key here.
 char c[28]="abcdefghijklmnopqrstuvwxyz! ";
 char str[]="hello world!";
 printf("%s\n", str);
 int i=0;
 int j=0;
 for(j=0;j<strlen(str);j++)
 {
  int p;
  for(i=0;i<28;i++)
  {
   if(str[j]==c[i])
   {
    p=i;
   }
  }
  int x = (p+key);
  int val = x%28;
  printf("%c", c[val]);
 }
 printf("\n");
}

Comments