#include #include #include #include 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(std::tolower(static_cast(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; }