≡ Menu

How to Write Caesar Cipher in C Program with Example Code

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.

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

{ 10 comments… add one }

  • mandrew December 8, 2014, 6:47 pm

    This is a really nice post and really helpful.
    I have a question though. From the example above you had a fixed shift of 3, but what if this number was much bigger? How would you write the code if you wanted to shift by 20 for example?

  • duskoKoscica December 19, 2014, 5:35 am

    In order to work on programmers tenacity, I would like to add few infos.
    1. All permutations of the set would not outperform the Caeser cypher you would be able to consider this.
    If you are trying to think of permutation as f, then your task would be to look for f^-1, which would be equivalent of decription. Instead of that, you could perform f^2, f^3, f^4,… f^n, which would lead you to identical transformation.

    2. Oh yes, you could be naive and think that f*g would lead you to more secure encription, but it is just matter of finding f*g=h, and now You could apply first step, and not worry about it, if you are Eva.

    3. So, what is beyond asimetric and quantum encription!

  • duskoKoscica January 17, 2015, 4:50 am

    @mandrev

    Nice, but you have missed the point, there is place for some other things.

    In professional application, which should be obvious from comment, I would not even care for that…
    There is statistical and some other attacks … that would penetrate this simple encryption…

    Well, if yo rally like to hear answer, I am without idea for something like that….

    hihhiiihiihihhhihihih!!!!!

    I hope you have some nice ideas to help me with this problem….

  • duskoKoscica January 17, 2015, 5:49 am

    Before I start, about my ideas I would like to listen to Lura.

    It is cool,

    perhaps this one> Fitiço di funana

    I am kind a stressed now!

  • duskoKoscica January 19, 2015, 5:59 am

    Ok!

    Fine, today I fell like to relaxed I need, for example>
    apocaliptica

    or some music like that.

    Why do you need that addition any way?!?

  • duskoKoscica January 20, 2015, 2:03 am

    Ok, even I have not used all excuses, and the subject of this article is a ceaser cypher, I will provide few answers.
    This problem is very serious, and it could be done in many ways, one of them would be to create some form of a table that could be implemented in form of matrix but that is not all of it, oh no, not at all.
    The second idea is to create one function that would produce shift for one place to left and if you go over the ‘z’ you return back to ‘a’.
    For some of us, it would be an introduction into topic of round buffer.
    But there is one more general way, that would serve as example how to generate more general algorithm that could be applied in more situations.
    Lets have cShift taken into our function, then you would use something like this
    cShift%=26; that will be used to shift our situation and loose some of periods that are not important in this disc.
    So, one of the important lines would be>
    if(islower(ch))
    if(ch + iShift &lt=’z’)
    ch+=iShift;
    else
    ch=(‘z’- 26 + iShift) + ‘a';

    THX for participating in our disc.

  • guy March 15, 2015, 11:38 pm

    To make the code wrap around a modulo 26 (% 26) is commonly used. But you have to start with ‘a’ as 0 and ‘z’ as 25. Otherwise it doesn’t work.

  • DuskoKoscica July 4, 2015, 6:21 am

    If you look more carefully, you would see there is condition for that.
    In the case you wish to achieve more complicated stuff, there are tables etc…

  • DuskoKoscica July 5, 2015, 6:20 am

    The condition is one that we make at the first.

    If there is a difference in alphabet length you could use alphabet length and wrap around in a buffer for example!

  • DuskoKoscica July 5, 2015, 11:57 am

    he program will handle only English letters and each input text will not be longer that one sentence.

    This part is one of the conditions we need for our example…

    Yes, there could be done way more, however the things would get way interesting for that intention…

    Have nice day, and fun!

Leave a Comment