≡ 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.

Add your comment

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

Comments on this entry are closed.

  • 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!

  • Daniel January 14, 2016, 7:04 am

    How can i compile this source code to get my result

  • Rene March 3, 2016, 7:40 am

    use gcc… or google to google it!

  • DuskoKoscica March 18, 2016, 7:24 am

    Now, you could find some stuff on this site

    http://www.scribd.com/doc/300013825/ENCRIPTION-DECRIPTION

    it is for free!

  • DuskoKoscica March 19, 2016, 11:27 am

    If have notice, in this method of encryption the message it self is a key.

    Well, it is different.

  • DuskoKoscica May 17, 2016, 6:24 am

    Standard decryption method could be applied on some other stuff, like>
    http://indy100.independent.co.uk/article/the-4000yearold-mystery-that-has-finally-been-solved–x1cNYgqRUg

    Now, if remember, …
    However I don’t think that it is solved, and strange thing that stuff in the boxes doesn’t repeat, to is it a prayer or a list prayer, or some list of …

  • DuskoKoscica May 18, 2016, 2:51 am

    Now when you have same letters or some parts of it and if you know old Greek you would be able to eliminate some of the possibilities and it is
    about time to crack that thing.
    I just don’t know why they needed 6 years, there are people who know it, even I had same idea, but I did not know Greek as a language.
    This way it is about high school kid to decipher it, just language, culture, old new Greek and some more things… that are very comnon!

  • sukhada July 5, 2016, 2:10 am

    the site is useful.
    to compile the program, if you are using linux,
    use
    to compile = gcc filename.c
    to run = ./a.out

  • unknown July 29, 2016, 2:02 am

    Plese!
    Don’t’ just don’t compile and run program like that.
    The program should not be named a’ which is genetic form or default..

  • Anonymous January 20, 2017, 9:31 am

    Here:

    #include
    #include
    #include
    void main()
    {
    	int k,j,i,h,u=0;
    	char plain[30],p[30],c[30],alpha[30]="abcdefghijklmnopqrstuvwxyz";
    	clrscr();
    	printf("**********Encryption**********");
    	printf("\nEnter the plain text = ");
    	gets(plain);
    	printf("Enter the key = ");
    	scanf("%d",&k);
    	for(i=0;i<strlen(plain);i++)
    	{
    		if(plain[i]==' ')      {
    			i++;u++;            }
    		for(j=0;j<strlen(alpha);j++)
    		{
    			if(alpha[j]==plain[i])
    			{
    			    h=(j+k)%26;
    			    c[i-u]=alpha[h];
    			   break;
    			}
    		}
    	}
    	c[i-u]='\0';
    	printf("\nCipher Text = ");
    	puts(c);
    	printf("**********Decryption**********");
    	for(i=0;i<strlen(c);i++)
    	{
    		for(j=0;j<strlen(alpha);j++)
    		{
    			if(alpha[j]==c[i])
    			{
    			    h=(j-k)%26;
    			    p[i]=alpha[h];
    			   break;
    			}
    		}
    	}
    	p[i]='\0';
    	printf("\nPlain Text = ");
    	puts(p);
    	getch();
    }
    
    /*
    **********Encryption**********
    Enter the plain text = hello hii
    Enter the key = 3
    
    Cipher Text = khoorkll
    **********Decryption**********
    Plain Text = hellohii
    */
    
  • DuskoKoscica June 7, 2017, 4:20 am

    Nice contribution, however there is some strange line: “clrscr();”, ah yeah it could be replaced by “clear()”.
    Somehow, it looks like “code or pre” tags wold unswallow that code you have added with that libraries….