Advertisement
Guest User

Untitled

a guest
Jul 16th, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1.     #include "cs50.h"
  2.     #include <ctype.h>
  3.     #include <stdio.h>
  4.     #include <stdlib.h>
  5.     #include <string.h>
  6.    
  7.     char substitution_encrypt (char c, char *key)
  8.     {
  9.             return isupper (c) ? toupper (key[c - 65]) : (islower (c) ? tolower (key[c - 97]) : c);
  10.     }
  11.    
  12.     void check_key (char *key)
  13.     {
  14.             if (strlen (key) != 26) {
  15.                     fprintf (stderr, "Invalid key");
  16.                     exit(EXIT_FAILURE);
  17.             }
  18.    
  19.             int letter_bitmap = 0;
  20.             for (char *c = key; *c != '\0'; c++) {
  21.                     char curr = *c;
  22.                     if (!isalpha (curr)) {
  23.                             fprintf (stderr, "Invalid key");
  24.                             exit (EXIT_FAILURE);
  25.                     }
  26.    
  27.                     if (isupper (curr))
  28.                             curr -= 65;
  29.                     else if (islower (curr))
  30.                             curr -= 97;
  31.    
  32.                     if (letter_bitmap & (1 << curr)) {
  33.                             fprintf (stderr, "Invalid key");
  34.                             exit (EXIT_FAILURE);
  35.                     }
  36.    
  37.                     letter_bitmap |= (1 << curr);
  38.             }
  39.     }
  40.    
  41.     int main (int argc, char **argv)
  42.     {
  43.             if (argc != 2) {
  44.                     fprintf (stderr, "Usage: ./substitution key\n");
  45.                     exit (EXIT_FAILURE);
  46.             }
  47.    
  48.             char *key = argv[1];
  49.    
  50.             check_key(key);
  51.    
  52.             char *text = get_string ("plaintext:  ");
  53.    
  54.             printf ("ciphertext: ");
  55.             while (*text) {
  56.                     putchar (substitution_encrypt (*text++, key));
  57.             }
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement