Program:
Caesar Cipher Encryption
#include <stdio.h>#include <ctype.h>int main(){char text[500], ch;int key;// taking user inputprintf("Enter a message to encrypt: ");scanf("%s", text);printf("Enter the key: ");scanf("%d", &key);// visiting character by characterfor (int i = 0; text[i] != '\0'; ++i){ch = text[i];// check for valid characterif (isalnum(ch)){// lower case charactersif (islower(ch)){ch = (ch - 'a' + key) % 26 + 'a';}// uppercase charactersif (isupper(ch)){ch = (ch - 'A' + key) % 26 + 'A';}// numbersif (isdigit(ch)){ch = (ch - '0' + key) % 10 + '0';}}// invalid characterelse{printf("Invalid Message");}// adding encoded answertext[i] = ch;}printf("Encrypted message: %s", text);return 0;}
Output:
Enter a message to encrypt: yZq8NS92mdREnter the key: 6Encrypted message: eFw4TY58sjX
Caesar Cipher Decryption
Output:#include <stdio.h>#include <ctype.h>int main(){char text[500], ch;int key;// taking user inputprintf("Enter a message to decrypt: ");scanf("%s", text);printf("Enter the key: ");scanf("%d", &key);// visiting each characterfor (int i = 0; text[i] != '\0'; ++i){ch = text[i];// check for valid charactersif (isalnum(ch)){// lower case charactersif (islower(ch)){ch = (ch - 'a' - key + 26) % 26 + 'a';}// uppercase charactersif (isupper(ch)){ch = (ch - 'A' - key + 26) % 26 + 'A';}// numbersif (isdigit(ch)){ch = (ch - '0' - key + 10) % 10 + '0';}}// invalid characterselse{printf("Invalid Message");}// asding decoded character backtext[i] = ch;}printf("Decrypted message: %s", text);return 0;}
Enter a message to decrypt: eFw4TY58sjX Enter the key: 6 Decrypted message: yZq8NS92mdR
0 Comments