DragonOsman

Vigenere's Cipher

Oct 14th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. // Osman Zakir
  2. // 10 15 2016
  3. // Introduction to Computer Science
  4. // Problem Set 2, vigenere.c
  5. // Take the key for the cipher from the user as a command-line argument and use it to encrypt a message
  6.  
  7. #include <cs50.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <ctype.h>
  11. #include <stdlib.h>
  12.  
  13. bool isletterstring(string key);
  14.  
  15. int main(int argc, string argv[])
  16. {
  17.     if (argc == 1 || argc > 2)
  18.     {
  19.         printf("Usage: ./vigenere <key>\n");
  20.         return 1;
  21.     }
  22.     string plaintext = GetString();
  23.     string key = argv[1];
  24.     const int key_size = strlen(key);
  25.     const int plaintext_size = strlen(plaintext);
  26.     char ciphertext[plaintext_size];
  27.     if (isletterstring(key))
  28.     {
  29.         for (int i = 0, j = 0; i < plaintext_size; i++)
  30.         {
  31.             if (j >= key_size)
  32.             {
  33.                 j = 0;
  34.             }
  35.             if (isalpha(plaintext[i]))
  36.             {
  37.                int k = toupper(key[j]) % 65;
  38.                int c = plaintext[i] + k;
  39.                if (toupper(c) > 'A')
  40.                {
  41.                    c -= 26;
  42.                }
  43.                ciphertext[i] = c;
  44.                j++;
  45.             }
  46.             else
  47.             {
  48.                 ciphertext[i] = plaintext[i];
  49.             }
  50.         }
  51.         printf("%s\n", ciphertext);
  52.     }
  53.     else
  54.     {
  55.         printf("Keyword must only contain letters A-Z and a-z\n");
  56.         return 1;
  57.     }
  58.     return 0;
  59. }
  60.  
  61. bool isletterstring(string key)
  62. {
  63.     for (int i = 0, n = strlen(key); i < n; i++)
  64.     {
  65.         if (!isalpha(key[i]))
  66.         {
  67.             return false;
  68.         }
  69.     }
  70.     return true;
  71. }
Add Comment
Please, Sign In to add comment