/* * Vigenere cipher */ #include #include #include #include #define N 128 int main(int argc, char *argv[]) { char buf[N+1], key[N+1], c; int i, shift, l, k, encrypt = 0; if (argc != 4) { fprintf(stderr, "Usage: %s (e|d) key text\n", argv[0]); exit(1); } if (!((strlen(argv[1]) == 1) && ((argv[1][0] == 'e') || (argv[1][0] == 'd')))) { fprintf(stderr, "Usage: %s (e|d) key text\n e indicates encryption, d - decryption", argv[0]); exit(1); } if (argv[1][0] == 'e') { encrypt = 1; } if (strlen(argv[2]) > N) { fprintf(stderr, "%s: key is too long, only the first %d bytes will be used\n", argv[0], N); } strncpy(key, argv[2], N); l = strlen(key); for (i = 0; i < l; i++) { if (!islower(key[i])) { fprintf(stderr, "%s: only lower case letters are allowed in key \n", argv[0]); exit(1); } } if (strlen(argv[3]) > N) { fprintf(stderr, "%s: text is too long, only the first %d bytes will be encrypted\n", argv[0], N); } strncpy(buf, argv[3], N); for (i = 0; i < strlen(buf); i++) { c = buf[i]; k = i % l; shift = key[k] - 'a'; if (!encrypt) { shift = 26 - shift; } if (islower(c)) { c = 'a' + (c - 'a' + shift)%26; } else if (isupper(c)) { c = 'A' + (c - 'A' + shift)%26; } printf("%c", c); } printf("\n"); return 0; }