Today we will learn the Caesar Cipher Algorithm Program in C with output & explanation. Ceaser Cipher is also named as shift cipher, Caesar shift or Caesar's code.
For example, if entered key is 2 then characters will be replaced by 2 characters down to it. Like, A will be replaced by C, B by D and so on. Below image show shifting of characters by key value 2.
Encryption & Decryption of a letter x by a shift n can be described mathematically as below.
/*Caesar Cipher Program in C*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void){
int key;
char plainText[101];
int i=0;
int cypherValue;
char cypher;
clrscr();
printf("Please enter the plain text you want to encrypt: ");
fgets(plainText, sizeof(plainText), stdin);
printf("\nPlease enter key: ");
scanf("%d",&key);
printf("\nThe ciphered text is : ");
while( plainText[i] != '\0' && strlen(plainText)-1 > i){
cypherValue = ((int)plainText[i] -97 + key) % 26 + 97;
cypher = (char)(cypherValue);
printf("%c", cypher);
i++;
}
printf("\n\n");
system("pause");
}
Output:#include<string.h>
#include<stdlib.h>
int main(void){
int key;
char plainText[101];
int i=0;
int cypherValue;
char cypher;
clrscr();
printf("Please enter the plain text you want to encrypt: ");
fgets(plainText, sizeof(plainText), stdin);
printf("\nPlease enter key: ");
scanf("%d",&key);
printf("\nThe ciphered text is : ");
while( plainText[i] != '\0' && strlen(plainText)-1 > i){
cypherValue = ((int)plainText[i] -97 + key) % 26 + 97;
cypher = (char)(cypherValue);
printf("%c", cypher);
i++;
}
printf("\n\n");
system("pause");
}
0 Comments