diff options
author | Tomasz Kramkowski <tk@the-tk.com> | 2015-04-02 02:23:14 +0200 |
---|---|---|
committer | Tomasz Kramkowski <tk@the-tk.com> | 2015-04-02 02:23:14 +0200 |
commit | a4a0b84f2765c19eae7d270e1627f4b00fa0a99a (patch) | |
tree | 3243b380663bec22ccdc7fc2a4bbf2deea627bb8 | |
parent | e60bdf760f69760501e826957d6dac053bccede5 (diff) | |
download | c-stuff-a4a0b84f2765c19eae7d270e1627f4b00fa0a99a.tar.gz c-stuff-a4a0b84f2765c19eae7d270e1627f4b00fa0a99a.tar.xz c-stuff-a4a0b84f2765c19eae7d270e1627f4b00fa0a99a.zip |
Simple implementation of vigenere cipher. (offset of 1 for desired results)
-rw-r--r-- | vigenere.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/vigenere.c b/vigenere.c new file mode 100644 index 0000000..8ed4a6c --- /dev/null +++ b/vigenere.c @@ -0,0 +1,62 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +#define CTOI(c) ((c) - 'A') +#define ITOC(c) ((c) + 'A') + +void preprocess(char *str); + +int main(int argc, char **argv) +{ + char *key, *ciphertext, *decodepos, *decodeneg; + long offset; + size_t keylength, textlength; + + if (argc != 4) { + fprintf(stderr, "Usage: %s <key> <offset> <ciphertext>\n", argv[0]); + exit(EXIT_FAILURE); + } + + key = argv[1]; + offset = strtol(argv[2], NULL, 10); + ciphertext = argv[3]; + + preprocess(key); + preprocess(ciphertext); + + keylength = strlen(key); + textlength = strlen(ciphertext); + + decodepos = malloc(textlength + 1); + decodeneg = malloc(textlength + 1); + + for (size_t i = 0; i < textlength; i++) { + decodepos[i] = ITOC((CTOI(ciphertext[i]) + offset + CTOI(key[i % keylength])) % 26); + decodeneg[i] = ITOC((CTOI(ciphertext[i]) + 52 - offset - CTOI(key[i % keylength])) % 26); + } + + decodepos[textlength] = '\0'; + decodeneg[textlength] = '\0'; + + printf("+ %s\n- %s\n", decodepos, decodeneg); + + free(decodepos); + free(decodeneg); + + return EXIT_SUCCESS; +} + +void preprocess(char *str) +{ + char *src = str, *dest = str; + + while (*src != '\0') { + if (isalpha(*src)) + *(dest++) = toupper(*src); + src++; + } + + *dest = '\0'; +} |