Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Implements the vigenere cipher: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
- */
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #define get_offset(ch) \
- (toupper((ch)) - 'A')
- #define fix_offset(off) \
- (((off) + ((off) < 0 ? 26 : 0)) % 26)
- #define encipher(text, key) \
- (cipher((text), (key), 0))
- #define decipher(text, key) \
- (cipher((text), (key), 1))
- typedef ssize_t offset;
- void
- cipher(char *text, char *key, int mode)
- {
- size_t keylen = strlen(key);
- size_t textlen = strlen(text);
- int outch;
- offset toff;
- offset koff;
- for(int i = 0, j = 0; i < textlen; i++, j++){
- toff = get_offset(text[i]);
- koff = get_offset(key[j % keylen]);
- outch = 'A' + fix_offset(toff + (mode ? -koff : +koff));
- if(isalpha(text[i]))
- putchar(outch);
- else {
- putchar(text[i]);
- j--;
- }
- }
- putchar('\n');
- }
- // TODO: add a UI
- // probably: vigenere key text [-i (read from stdin) -e (encipher [default]) -d (decipher) -- (start ignoring '-')]
- // Functions/objects probably to implement: usage, parse_arg, parse_opt, find_arg, dispatch table {flag, descr, callback}
- // Probably just copy it from the other cipher I made
- int
- main(int argc, char **argv)
- {
- char *plaintext = "What is a man without knowing the rich aroma of the future; the hot, complex balance of the present; and the bittersweet aftertaste of the past?";
- char *key = "LIBITINA";
- encipher(plaintext, key);
- //sanity testing to make sure the program didn't suddenly break
- encipher("attackatdawn", "lemon");
- decipher("LXFOPVEFRNHR", "lemon");
- encipher("Attack At Dawn!", "lemon");
- decipher("LXFOPV EF RNHR!", "lemon");
- encipher("Attack At 420 Dawn!", "lemon");
- decipher("LXFOPV EF 420 RNHR!", "lemon");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement