# C program to implement Caesar Cipher Algorithm

Caesar Cipher is one of the most basic forms of Encryption Algorithm, In this type of Encryption, each letter in the message is replaced with a letter corresponding to a certain number of letters up or down in the alphabet. For example, we have the following message

Hello

Encrypted Version

Ebiil

In the above message, we replaced every character with its previous 3rd value according to ASCII. for example ‘H’ will be replaced by ‘E’.

We will make two functions to perform Encryption and Decryption in C, So without waiting let’s get our hands dirty.

Encrypt()

``void encrypt(char arr[]){ int i,j; for(i=0;i<strlen(arr);i++){ if(arr[i]==' ') continue; for(j=0;j<STEP;j++){ arr[i]--; if(arr[i]<97 && arr[i] > 90) arr[i] = 122; if(arr[i] < 65) arr[i] = 90; }  } }``

The following function will modify each character and reduce it to three places.

Decrypt()

``void decrypt(char arr[]){ int i,j; for(i=0;i<strlen(arr);i++){ if(arr[i]==' ') continue; for(j=0;j<STEP;j++){ arr[i]++; if(arr[i]>122) arr[i] = 97; if(arr[i] > 90 && arr[i]<97) arr[i] = 65; }  } }``

The following function will modify each character and increase it to three places. Note: this function should not be used before `Encrypt` function.

Now will use the above functions and write a full C program for it.

C program to perform Caesar Cipher Encryption

``#include<stdio.h> #include<stdlib.h> #include<string.h> #define STEP 3  int check(char arr[]){ int i; for(i=0;i<strlen(arr);i++){ if((arr[i]>='A' && arr[i]<='Z') | (arr[i]>='a' && arr[i]<='z')) continue; else return 0; } return 1; }   void encrypt(char arr[]){ int i,j; for(i=0;i<strlen(arr);i++){ if(arr[i]==' ') continue; for(j=0;j<STEP;j++){ arr[i]--; if(arr[i]<97 && arr[i] > 90) arr[i] = 122; if(arr[i] < 65) arr[i] = 90; }  } } void decrypt(char arr[]){ int i,j; for(i=0;i<strlen(arr);i++){ if(arr[i]==' ') continue; for(j=0;j<STEP;j++){ arr[i]++; if(arr[i]>122) arr[i] = 97; if(arr[i] > 90 && arr[i]<97) arr[i] = 65; }  } } int main(){ char msg; printf("Enter your message:"); scanf ("\%[^]s", arr); if(!check(msg)) printf("Invalid Characters present in the message."); else{ printf("Encrypted Version"); encrypt(msg); printf("\%s",msg); printf("Decrypt Version"); decrypt(msg); printf("\%s",msg); } return 0; } ``

Output

``Enter your message:psychocodes Encrypted Version mpvzelzlabp Decrypt Version psychocodes``

Also, don’t forget to subscribe to our Newsletter.

Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Explaining Register variables in C with examples
17 August 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями: