Caesar Cipher in C [Encryption & Decryption]

What is Caesar Cipher ?

It is one of the simplest encryption technique in which each character in plain text is replaced by a character some fixed number of positions down to it.

For example, if key is 3 then we have to replace character by another character that is 3 position down to it. Like A will be replaced by D, C will be replaced by F and so on.

For decryption just follow the reverse of encryption process.
image

Program for Caesar Cipher in C

Encryption

#include<stdio.h>

int main()
{
char message[100], ch;
int i, key;

printf("Enter a message to encrypt: ");
gets(message);
printf("Enter key: ");
scanf("%d", &key);

for(i = 0; message[i] != '\0'; ++i){
	ch = message[i];
	
	if(ch >= 'a' && ch <= 'z'){
		ch = ch + key;
		
		if(ch > 'z'){
			ch = ch - 'z' + 'a' - 1;
		}
		
		message[i] = ch;
	}
	else if(ch >= 'A' && ch <= 'Z'){
		ch = ch + key;
		
		if(ch > 'Z'){
			ch = ch - 'Z' + 'A' - 1;
		}
		
		message[i] = ch;
	}
}

printf("Encrypted message: %s", message);

return 0;
}

Decryption

#include<stdio.h>

int main()
{
char message[100], ch;
int i, key;

printf("Enter a message to decrypt: ");
gets(message);
printf("Enter key: ");
scanf("%d", &key);

for(i = 0; message[i] != '\0'; ++i){
	ch = message[i];
	
	if(ch >= 'a' && ch <= 'z'){
		ch = ch - key;
		
		if(ch < 'a'){
			ch = ch + 'z' - 'a' + 1;
		}
		
		message[i] = ch;
	}
	else if(ch >= 'A' && ch <= 'Z'){
		ch = ch - key;
		
		if(ch < 'A'){
			ch = ch + 'Z' - 'A' + 1;
		}
		
		message[i] = ch;
	}
}

printf("Decrypted message: %s", message);

return 0;
}
7 Likes

Great post … easy to understand code. Please write AES 256 bit encryption/decryption in C/C++ if possible.

2 Likes

@landi58 Here’s an implementation in C you can study. Tiny-AES

1 Like

This topic was automatically closed after 121 days. New replies are no longer allowed.