-
-
Save behrtam/5115222 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef char* string; | |
string encrypt(int offset, string text); | |
string decrypt(int offset, string text); | |
/* Programmaufruf: ceasar [-d|-e] [offset] [text ...] | |
* Beispiel: | |
* ./ceasar -e 2 abyz | |
* >> cdab | |
* | |
* ./ceasar -d 2 cdab | |
* >> abyz | |
*/ | |
int main(int argc, char* argv[]) | |
{ | |
// ToDo: Aufrufparameter besser validieren | |
if (argc < 3 || !(argv[1][1] == 'e' || argv[1][1] == 'd')) | |
return 1; | |
for (int i = 3; i < argc; ++i) | |
{ | |
string text; | |
if (strcmp(argv[1], "-e") == 0) | |
text = encrypt(atoi(argv[2]), argv[i]); | |
else if (strcmp(argv[1], "-d") == 0) | |
text = decrypt(atoi(argv[2]), argv[i]); | |
printf("%s ", text); | |
// allokierten Speicher wieder freigeben | |
free(text); | |
} | |
putchar('\n'); | |
} | |
string decrypt(int offset, string text) | |
{ | |
return encrypt(offset * (-1), text); | |
} | |
string encrypt(int offset, string text) | |
{ | |
int text_len = strlen(text); | |
// Speicher allokieren für jedes Zeichen in 'text' | |
// und +1 um das char-Array später zu terminieren ('\0') | |
string encrypted_text = malloc(sizeof(char) * (text_len + 1)); | |
strcpy(encrypted_text, text); | |
for (int i = 0; i < text_len; ++i) | |
{ | |
int ascii_value = (int) encrypted_text[i]; | |
// das '% 26' sorgt dafür, dass bei Überscheitung des Z-ASCII-Wertes | |
// das Alphabet wieder von vorne durchwandert wird | |
if (ascii_value >= 65 && ascii_value <= 90) // UPPERCASE | |
encrypted_text[i] = (char)((ascii_value - 65 + offset) % 26 + 65); | |
else if (ascii_value >= 97 && ascii_value <= 122) // lowercase | |
encrypted_text[i] = (char)((ascii_value - 97 + offset) % 26 + 97); | |
// else => alle nicht Buchstaben werden nicht verschlüsselt | |
} | |
// string '\0'-terminieren | |
encrypted_text[text_len] = '\0'; | |
return encrypted_text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment