C Program to Implement Caesar Cipher

Caesar Cipher Program in C: The Caesar Cipher technique is the simplest and oldest method of encryption technique in cryptography. In this technique, we are given a text which we have to encrypt by shifting the characters by some fixed number of positions.

For example, if the shift position is 2 then every character will be shifted by 2 positions to the right.

Plain:

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

Cipher:

C D E F G H I J K L M N O P Q R S T U V W X Y Z A B
Algorithm for Caesar Cipher:
  1. Traverse the entire text letter by letter.
  2. On every iteration, the character is transformed as per the rule, depending upon whether you are encrypting or decrypting the text.
  3. Return the newly updated string.
Problem Statement

Write a C program to perform the encryption and decryption of a message using the Ceaser Cipher technique.

Problem Solution

To perform the cipher technique in a given message, we have to find the integer value corresponding to the given text. Then we will use the modulo operator to perform the shift operation which does not exceed the limit of characters which is 0 to 25.

The corresponding integer value of each character is given below:

advertisement
advertisement
A B C D E F G H I J K L M
0 1 2 3 4 5 6 7 8 9 10 11 12
N O P Q R S T U V W X Y Z
13 14 15 16 17 18 19 20 21 22 23 24 25

There are several ways to implement the Caesar Cipher in C language. Let’s take a detailed look at all the approaches to encrypt and decrypt the text using Caesar Cipher method.

Method 1: (Simple Approach)
Program/Source Code

Here is source code of the C Program to Implement Caesar Cipher. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. #define MAXSIZE 1024
  5.  
  6. void encrypt(char*);
  7. void decrypt(char*);
  8.  
  9. int menu();
  10.  
  11. int main(void) {
  12.  
  13.     char c, choice[2], s[MAXSIZE];
  14.  
  15.     while (1) {
  16.         menu();
  17.  
  18.         gets(choice);
  19.  
  20.         if ((choice[0] == 'e') || (choice[0] == 'E')) {
  21.             puts("Input text to encrypt->");
  22.             gets(s);
  23.             encrypt(s);
  24.         } else if ((choice[0] == 'd') || (choice[0] == 'D')) {
  25.             puts("Input text to decrypt->");
  26.             gets(s);
  27.             decrypt(s);
  28.         } else
  29.             break;
  30.     }
  31.  
  32.     return 0;
  33. }
  34.  
  35. void encrypt(char*str) {
  36.     int n = 0;
  37.     char *p = str, q[MAXSIZE];
  38.  
  39.     while (*p) {
  40.         if (islower(*p)) {
  41.             if ((*p >= 'a') && (*p < 'x'))
  42.                 q[n] = toupper(*p + (char) 3);
  43.             else if (*p == 'x')
  44.                 q[n] = 'A';
  45.             else if (*p == 'y')
  46.                 q[n] = 'B';
  47.             else
  48.                 q[n] = 'C';
  49.         } else {
  50.             q[n] = *p;
  51.         }
  52.         n++;
  53.         p++;
  54.     }
  55.     q[n++] = '\0';
  56.     puts(q);
  57. }
  58.  
  59. void decrypt(char*str) {
  60.     int n = 0;
  61.     char *p = str, q[MAXSIZE];
  62.  
  63.     while (*p) {
  64.         if (isupper(*p)) {
  65.             if ((*p >= 'D') && (*p <= 'Z'))
  66.                 q[n] = tolower(*p - (char) 3);
  67.             else if (*p == 'A')
  68.                 q[n] = 'x';
  69.             else if (*p == 'B')
  70.                 q[n] = 'y';
  71.             else
  72.                 q[n] = 'z';
  73.         } else {
  74.             q[n] = *p;
  75.         }
  76.         n++;
  77.         p++;
  78.     }
  79.     q[n++] = '\0';
  80.     puts(q);
  81. }
  82.  
  83. int menu() {
  84.     puts("To encrypt, input e or E\n");
  85.     puts("To decrypt, input d or D\n");
  86.     puts("To exit, input any other letter\n");
  87.     puts("Your choice:->\n");
  88.     return 0;
  89. }
Program Explanation:

1. This program uses the Caesar cipher to encrypt and decrypt messages.
2. It offers users a menu to select between encryption or decryption and requests text input.
3. Following user input, the program utilizes the Caesar cipher, shifting each alphabet letter by three positions.
4. Finally, it shows the changed message, demonstrating how the Caesar cipher works for coding and decoding text.

Note: Join free Sanfoundry classes at Telegram or Youtube
Program Output:
$ gcc CaesarCipher.c
$ ./a.out
 
To encrypt, input e or E
To decrypt, input d or D
To exit, input any other letter
Your choice:-> e
Input text to encrypt-> DharmendraHingu
 
DKDUPHQGUDHLQJX
 
To encrypt, input e or E
To decrypt, input d or D
To exit, input any other letter
Your choice:-> x

Method 2: (Optimized Approach)

In this approach, we will use the modulo operator to perform the shift operation which does not exceed the limit of characters which is 0 to 25.

Program/Source Code

Here is the C program implementation of the Caesar Cipher technique for encryption and decryption. We have discussed the program in detail below the code.

advertisement
  1. /*
  2.  * C Program to Implement Caesar Cipher
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. // function prototyping
  8. void encrypt(char*, int);
  9. void decrypt(char*, int);
  10. void tolower_case(char*);
  11. int isAlpha(char);
  12.  
  13. // main function
  14. int main()
  15. {
  16.     char text[50];
  17.     int shift_by;
  18.  
  19.     printf("Enter your text: ");
  20.     gets(text);
  21.  
  22.     fflush(stdin);
  23.     printf("Encrypt by how much shift: ");
  24.     scanf("%d", &shift_by);
  25.  
  26.     // max shift is 26
  27.     shift_by = shift_by % 26;
  28.  
  29.     // encrypting the text 
  30.     encrypt(text, shift_by);
  31.     printf("\n\nEncrypted Text:\n%s\n", text);
  32.  
  33.     // decrypting the text
  34.     decrypt(text, shift_by);
  35.     printf("\nDecrypted Text:\n%s", text);
  36.     return 0;
  37. }
  38.  
  39. // function to encrypt the text
  40. void encrypt(char* text, int shift)
  41. {
  42.     char* ch = text;
  43.     int i = 0;
  44.     // convert into lowercase string
  45.     tolower_case(text);
  46.  
  47.     while(*ch != '\0')
  48.     {
  49.         // encrypt only alphabet characters by shifting their positions
  50.         if(text[i] != ' ' && isAlpha(text[i]))
  51.         {
  52.             text[i] = 'a' + (text[i] - 'a' + shift) % 26;
  53.         }
  54.         i += 1;
  55.         ch++;
  56.     }
  57. }
  58.  
  59. // function to decrypt the text
  60. void decrypt(char* text, int shift)
  61. {
  62.     char* ch = text;
  63.     int i = 0;
  64.     tolower_case(text);
  65.  
  66.     while(*ch != '\0')
  67.     {
  68.         // skip the whitespace and non-alphabet characters
  69.         if(text[i] == ' ' || !isAlpha(text[i]))
  70.         {
  71.             text[i] = text[i];
  72.         } 
  73.         // if character is reaching to the last alphabet character
  74.         else if(text[i] - shift < 'a')
  75.         {
  76.             text[i] = 'z' - ('a' - (text[i] - shift + 1));
  77.         }
  78.         else
  79.         {
  80.             text[i] = text[i] - shift;
  81.         }
  82.  
  83.         i += 1;
  84.         ch += 1;
  85.     }
  86. }
  87.  
  88. // function to check whether the character is alphabet or not
  89. int isAlpha(char ch)
  90. {
  91.     if(ch >= 'a' && ch <= 'z')
  92.     {
  93.         return 1;
  94.     }
  95.     if(ch >= 'A' && ch <= 'Z')
  96.     {
  97.         return 1;
  98.     }
  99.     return 0;
  100. }
  101.  
  102. // function to convert the string into lowercase
  103. void tolower_case(char* text)
  104. {
  105.     char* ch = text;
  106.     while(*ch != '\0')
  107.     {
  108.         if(*ch >= 'A' && *ch <= 'Z')
  109.         {
  110.             *ch = *ch + 32;
  111.         }
  112.         ch++;
  113.     }
  114. }
Program Explanation

In the above program we have perform the encryption and decryption operation of a text. Let’s understand how these functions work:

Encryption Method

To encrypt the text, we need to shift the character by some places. To shift the characters we have to increment their ASCII values by n, where n is the number of shifts that we want to do.

Here is an example of shifting the text message by 3 places.

Text: hello

advertisement
Normal h e l l o
ASCII value 104 101 108 108 111
Shifted 107 104 111 111 114
Encrypted k h o o r

Encrypted Message: khoor

Time Complexity: O(n)
Linear time complexity to encrypt the text. Here, n is the length of the text.

Space Complexity: O(1)
It takes constant space to encrypt the text.

Decryption Method

To decrypt the message, we have to shift back the position of characters by the given position.

Let’s decrypt the encrypted message by position 3.

Encrypted Message: khoor

Encrypted k h o o r
ASCII value 104 101 108 108 111
Decrypted 107 104 111 111 114
Normal h e l l o

Text: hello

Time Complexity: O(n)
It takes the linear amount of time to decrypt the text from the encrypted text. Here, n is the length of a string.

Space Complexity: O(1)
Since we are using only normal variables, the space complexity is constant.

Run Time Testcases

In this case, we are encrypting and decrypting text using Caesar Cipher algorithm.

Enter your text: hello
Encrypt by how much shift: 3
Encrypted Text:
khoor
 
Decrypted Text:
hello

Advantages of Caesar Cipher:

  • It is easy to build this message and message can be easily encrypted and decrypted in this method.
  • It provides minimum security to the information.
  • The system does not need to code is complicated.
  • It requires less number of computing resources.
  • It takes less time for encryption and decryption.

Disadvantages of Caesar Cipher:

  • It has a very simple structure usage.
  • It can only provide the minimum security to the information.
  • Security is a big issue with this method.

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.