Advertisement
Guest User

vigenere

a guest
Jul 20th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. char shift_character(char c, char key);
  7.  
  8. int main(int argc, string argv[])
  9. {
  10.     if (argc != 2)
  11.     {
  12.         printf("Usage: ./vigenere k\n");
  13.         return 1;
  14.     }
  15.     string key = argv[1];
  16.     int key_index = 0;
  17.     int max_index = strlen(key) - 1;
  18.     for (int i = 0; i <= max_index; i++)
  19.     {
  20.         if (!isalpha(key[i]))
  21.         {
  22.             return 1;
  23.         }
  24.     }
  25.  
  26.     string plain_text = get_string("plaintext: ");
  27.     printf("ciphertext: ");
  28.     for (int i = 0, input_length = strlen(plain_text); i < input_length; i++)
  29.     {
  30.         if (!isalpha(plain_text[i]))
  31.         {
  32.             printf("%c", plain_text[i]);
  33.             continue;
  34.         }
  35.         printf("%c", shift_character(plain_text[i], key[key_index]));
  36.         key_index++;
  37.         if (key_index > max_index)
  38.         {
  39.             key_index = 0;
  40.         }
  41.     }
  42.     printf("\n");
  43. }
  44.  
  45. char shift_character(char c, char key)
  46. {
  47.     key = toupper(key) - 'A';
  48.     int offset = ((islower(c)) ? 'a' : 'A');
  49.     int alphabit_index = c - offset;
  50.     int shifted_alpha_index = (alphabit_index + key) % 26;
  51.     return shifted_alpha_index + offset;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement