Advertisement
B1KMusic

vigenere.c (incomplete)

Feb 23rd, 2018
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. /* Implements the vigenere cipher: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
  2.  */
  3.  
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include <string.h>
  7.  
  8. #define get_offset(ch) \
  9.     (toupper((ch)) - 'A')
  10.  
  11. #define fix_offset(off) \
  12.     (((off) + ((off) < 0 ? 26 : 0)) % 26)
  13.  
  14. #define encipher(text, key) \
  15.     (cipher((text), (key), 0))
  16.  
  17. #define decipher(text, key) \
  18.     (cipher((text), (key), 1))
  19.  
  20. typedef ssize_t offset;
  21.  
  22. void
  23. cipher(char *text, char *key, int mode)
  24. {
  25.     size_t keylen = strlen(key);
  26.     size_t textlen = strlen(text);
  27.     int outch;
  28.     offset toff;
  29.     offset koff;
  30.  
  31.     for(int i = 0, j = 0; i < textlen; i++, j++){
  32.         toff = get_offset(text[i]);
  33.         koff = get_offset(key[j % keylen]);
  34.         outch = 'A' + fix_offset(toff + (mode ? -koff : +koff));
  35.  
  36.         if(isalpha(text[i]))
  37.             putchar(outch);
  38.  
  39.         else {
  40.             putchar(text[i]);
  41.             j--;
  42.         }
  43.     }
  44.  
  45.     putchar('\n');
  46. }
  47.  
  48. // TODO: add a UI
  49. // probably: vigenere key text [-i (read from stdin) -e (encipher [default]) -d (decipher) -- (start ignoring '-')]
  50. // Functions/objects probably to implement: usage, parse_arg, parse_opt, find_arg, dispatch table {flag, descr, callback}
  51. // Probably just copy it from the other cipher I made
  52.  
  53. int
  54. main(int argc, char **argv)
  55. {
  56.     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?";
  57.     char *key = "LIBITINA";
  58.  
  59.     encipher(plaintext, key);
  60.     //sanity testing to make sure the program didn't suddenly break
  61.     encipher("attackatdawn", "lemon");
  62.     decipher("LXFOPVEFRNHR", "lemon");
  63.     encipher("Attack At Dawn!", "lemon");
  64.     decipher("LXFOPV EF RNHR!", "lemon");
  65.     encipher("Attack At 420 Dawn!", "lemon");
  66.     decipher("LXFOPV EF 420 RNHR!", "lemon");
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement