Created
March 4, 2023 10:23
-
-
Save hansputera/bd9f00163bf424aadaab303d0d27fc9b to your computer and use it in GitHub Desktop.
Caesar cipher impl
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 <cstring> | |
| #include <iostream> | |
| #include <algorithm> | |
| #include <cstdlib> | |
| static const char chars[26][2] = { | |
| "a", | |
| "b", | |
| "c", | |
| "d", | |
| "e", | |
| "f", | |
| "g", | |
| "h", | |
| "i", | |
| "j", | |
| "k", | |
| "l", | |
| "m", | |
| "n", | |
| "o", | |
| "p", | |
| "q", | |
| "r", | |
| "s", | |
| "t", | |
| "u", | |
| "v", | |
| "w", | |
| "x", | |
| "y", | |
| "z" | |
| }; | |
| static int find_pos_from_char(char *item) | |
| { | |
| for (int i = 0; i < sizeof(chars)/sizeof(chars[0]); i++) | |
| { | |
| if (*chars[i] == *item) | |
| { | |
| return i; | |
| } | |
| } | |
| return -1; | |
| } | |
| // n = shift | |
| // plain_src = text source | |
| static int caesar_exec(int n, int eod, char* plain_src) | |
| { | |
| if (n > (sizeof(chars)/sizeof(chars[0]))) { | |
| return -1; | |
| } else if (n < 1) { | |
| n = 23; | |
| } | |
| if (eod < 0 || eod > 1) | |
| { | |
| // 0 = e | |
| // 1 = d | |
| eod = 0; | |
| } | |
| for (int i = 0; i < strlen(plain_src); i++) | |
| { | |
| if (!std::isspace(plain_src[i])) | |
| { | |
| plain_src[i] = static_cast<char>(std::tolower(static_cast<char>(plain_src[i]))); | |
| if (eod == 0) { | |
| plain_src[i] = *chars[(find_pos_from_char(&plain_src[i]) + n) % 26]; | |
| } else { | |
| plain_src[i] = *chars[std::abs((find_pos_from_char(&plain_src[i]) - n) % 26)]; | |
| } | |
| } | |
| } | |
| return 0; | |
| } | |
| int main() | |
| { | |
| char text[] = "abcdefghijklmnopqrstuvwyz"; | |
| if (caesar_exec(23, 0, text) != -1) { | |
| std::cout << text << std::endl; | |
| // decrypt | |
| if (caesar_exec(23, 1, text) != -1) { | |
| std:: cout << text << std::endl; | |
| } else { | |
| std::cout << "fail to decrypt"; | |
| } | |
| } else { | |
| std::cout << "fail to encrypt"; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment