Created
May 5, 2024 21:25
-
-
Save pedrol2b/d8c6e2d8dd18756efbe135d13c0b71eb to your computer and use it in GitHub Desktop.
Caesar's cipher algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/********************************************************************** | |
* | |
* caesar.c | |
* Caesar's cipher algorithm | |
* Encrypts messages using Caesar's cipher. | |
* <@pedrol2b> | |
**********************************************************************/ | |
char *encode(char str[], int key) | |
{ | |
int i; | |
char buff[256]; | |
for (i = 0; str[i] != '\0'; i++) | |
{ | |
if (str[i] >= 'a' && str[i] <= 'z') | |
buff[i] = (str[i] - 'a' + key) % 26 + 'a'; | |
else if (str[i] >= 'A' && str[i] <= 'Z') | |
buff[i] = (str[i] - 'A' + key) % 26 + 'A'; | |
else | |
buff[i] = str[i]; | |
str[i] = buff[i]; | |
} | |
return str; | |
} | |
char *decode(char str[], int key) | |
{ | |
int i; | |
char buff[256]; | |
for (i = 0; str[i] != '\0'; i++) | |
{ | |
if (str[i] >= 'a' && str[i] <= 'z') | |
buff[i] = (str[i] - 'a' - key) % 26 + 'a'; | |
else if (str[i] >= 'A' && str[i] <= 'Z') | |
buff[i] = (str[i] - 'A' - key) % 26 + 'A'; | |
else | |
buff[i] = str[i]; | |
str[i] = buff[i]; | |
} | |
return str; | |
} | |
int main(void) | |
{ | |
int option, key = 0; | |
char str[256]; | |
printf("Caesar Cipher Algorithm\n"); | |
printf("---------------------\n"); | |
printf("Options:\n"); | |
printf("1. Encrypt a text\n"); | |
printf("2. Decrypt a text\n"); | |
printf("---------------------\n"); | |
printf("Usage: First enter the option number, then the key, and finally the text to encrypt/decrypt.\n"); | |
printf("Example: To encrypt the text 'hello' with a key of 3, you would enter:\n"); | |
printf("1\n3\nhello\n"); | |
printf("---------------------\n"); | |
printf("Please enter your option, key, and text:\n"); | |
scanf("%d\n%d\n%s", &option, &key, str); | |
switch (option) | |
{ | |
case 1: | |
printf("%s\n", encode(str, key)); | |
break; | |
case 2: | |
printf("%s\n", decode(str, key)); | |
break; | |
default: | |
printf("Invalid option.\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment