How to Write Caesar Cipher in C Program with Example Code

by Koscica Dusko on August 7, 2014

There are three types of cryptography techniques :

  1. Secret key Cryptography
  2. Public key cryptography
  3. Hash Functions


We discussed about the above techniques earlier in the Cryptography basics article.

One simple and basic method to encrypt a message is using Caesar’s cipher. It is a very simple form of encryption, where we take letters one by one from the original message and translate it into an encrypted text.

In this article, you’ll learn how to create a C program code that will encrypt and decrypt the text using Caesars cipher.

In this example, on a high-level, we will do the following:

  • The source text that needs to be encrypted is given in lower case. But if you need to decrypt the text, it should be given in upper case.
  • When it is encrypted, each letter will have its ANSII code increased for tree places. When it is decrypted, it will have its code moved toward left.
  • The letter ‘x’ will be translated into ‘A’, the letter ‘y’ is transformed into the letter ‘B’, and the ‘z’ will change into ‘C’.
  • We are keeping this logic very simple so that we can understand the code. Once you get the hang of it, come-up with more complex logic to encrypt and decrypt.
  • The program will handle only English letters and each input text will not be longer that one sentence. At the end of the input sentence it should have the marker for end ‘.’.
  • If you don’t have the sense marker, the longest sentence is 1024 letters long. This is some form of protection, which would prevent the user to input the sentence that would over populate size of the program.
  • The numbers in the input will not be changed.
  • The blank symbol or any non letter symbol will not be changed.

The following is an example of input text that needs to be encrypted:

this is a test message.

The following is the output decrypted text for the above input in Caesar’s cipher.

WLV LV D WHVW PHVVDJH.

The decryption is reverse. If you input the encrypted text, you should get decrypted text as the output.

C Source Code Example for Ceaser Cipher

#include <stdio.h>
#include <ctype.h>

#define MAXSIZE 1024

void encrypt(char*);
void decrypt(char*);

int menu();

int
main(void)
{

char c,
     choice[2],
     s[MAXSIZE];

 while(1)
 {
 menu();

 gets(choice);

 if((choice[0]=='e')||(choice[0]=='E'))
 {
  puts("Input text to encrypt->");
  gets(s);
  encrypt(s);
 }
 else if((choice[0]=='d')||(choice[0]=='D'))
 {
  puts("Input text to decrypt->");
  gets(s);
  decrypt(s);
 }
 else
    break;
 }

 return 0;
}

void encrypt(char*str)
{
	int n=0;
	char *p=str,
		 q[MAXSIZE];

	while(*p)
	{
	 if(islower(*p))
	 {
		 if((*p>='a')&&(*p<'x'))
			 q[n]=toupper(*p + (char)3);
		 else if(*p=='x')
			 q[n]='A';
		 else if(*p=='y')
			 q[n]='B';
		 else
			 q[n]='C';
	 }
	 else
	 {
		 q[n]=*p;
	 }
	 n++; p++;
	}
	q[n++]='\0';
	puts(q);
}

void decrypt(char*str)
{
	int   n=0;
	char *p=str,
		 q[MAXSIZE];

	while(*p)
	{
	 if(isupper(*p))
	 {
		 if((*p>='D')&&(*p<='Z'))
			 q[n]=tolower(*p - (char)3);
		 else if(*p=='A')
			 q[n]='x';
		 else if(*p=='B')
			 q[n]='y';
		 else
			 q[n]='z';
	 }
	 else
	 {
		 q[n]=*p;
	 }
	 n++; p++;
	}
	q[n++]='\0';
	puts(q);
}

int menu()
{
 puts("To encrypt, input e or E\n");
 puts("To decrypt, input d or D\n");
 puts("To exit, input any other letter\n");
 puts("Your choice:->\n");
 return 0;
}

Code Analysis

The main function does the following:

  • First we include the stdio.h and ctype.h
  • Then we create a macro for maximum sentence size. In this example, it is 1024.
  • There are a few declarations to reserve place for things that we use in our code.
  • While loop will repeat until user inputs proper letter to stop the program.
  • In the while loop, we call the function menu(), which will display the menu to the user.

Next, it does the following:

  • When you input the letter, function gets() reads your choice. According to the user input appropriate function would be called.
  • One function encrypts the text, and the other function decrypts it.
  • First function gets one string into it, and modifies it. After that, we are changing each letter according to the rule we need to apply.
  • The pointer q is a helper to read the original string, and the q is used to store the output.
  • tolower() will transform the letter into lower case. toupper() will transform the letter into upper case.
  • Function gets() is used to read the input string from user.

Now, to the function encrypt:

  • To encrypt, this code will move letters to a different offset by 3 spaces in ASCII table. Also, at the end of alphabet you wrap around and replace: x, y and z, with: a, b and c.
  • Instead of char type, use wcahr_t symbols that could be good for languages other than English. There are usually similar functions that will work with two byte letters. Sometimes it is enough to use one additional w.

As an additional exercise, modify the above C sample code to include different offsets in one sentence itself.

When we talk about breaking Caesars cipher, first algorithm that could be applied is statistical decryption. For each language, there are usual frequencies of each letter and they could be used to figure out the encrypted text without getting the key. On a related subject, you should also explore how Vigener’s cipher works.

Again, it is very easy to break the encrypted text generated by this example. The above code is given only for learning purpose to understand how this works.


Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: