Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <ctype.h>
- #include <stdio.h>
- #include <string.h>
- int quit(void);
- char *hash(string argv, string plaintext, string encodedtext);
- int calc_checksum(void);
- int main(int argc, string argv[])
- {
- int checksum = calc_checksum();
- int hashsum = 0;
- if (argc != 2 || strlen(argv[1]) != 26) // Basic checks for arguments
- {
- return quit(); // Exit case 1 - if argument count mismatch
- }
- else
- {
- for (int i = 0; i < 26; i++)
- {
- if (isalpha(argv[1][i]))
- {
- hashsum += toupper(argv[1][i]); // To save me the hassle i have calculated the hashes in uppercase
- }
- else
- {
- return quit(); // Exit case 2 - if Any number is in the key
- }
- }
- if (hashsum == checksum)
- {
- string plaintext = get_string("plaintext: ");
- char encodedtext[strlen(plaintext)];
- printf("ciphertext: %s\n", hash(argv[1], plaintext, encodedtext));
- }
- else
- {
- return quit(); // Exit case 3 - if the hashes dont match
- }
- }
- }
- int quit(void)
- {
- printf("Usage ./substitution Key\n");
- return 1;
- }
- char *hash(string argv, string plaintext, string encodedtext)
- {
- char key[26];
- for (int i = 0; i < strlen(plaintext); i++)
- {
- if (isupper(plaintext[i]))
- {
- for (int n = 65, j = 0; n <= 90; j++, n++)
- {
- if (plaintext[i] == n) // This figures out which alphabet it is
- {
- encodedtext[i] =
- toupper(argv[j]); // This figures out what key value to be replaced with
- }
- else
- {
- continue;
- }
- }
- }
- else if (isdigit(plaintext[i]) || !(isalpha(plaintext[i])))
- {
- encodedtext[i] = plaintext[i]; // no replacement happens
- }
- else
- {
- for (int n = 97, j = 0; n <= 122; j++, n++)
- {
- if (plaintext[i] == n)
- {
- encodedtext[i] =
- tolower(argv[j]); // This figures out what key value to be replaced with
- }
- else if(plaintext[i] == ' ') {
- encodedtext[i] = ' '; // For not neglecting the space in the user text
- }
- else
- {
- continue;
- }
- }
- }
- }
- encodedtext[strlen(plaintext)] = '\0';
- return encodedtext;
- }
- int calc_checksum(void)
- {
- int sum = 0;
- for (int i = 65; i < 91; i++)
- {
- sum += i;
- }
- return sum;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement