CS50_Labs/Lab2/substitution/substitution.c

96 lines
2.7 KiB
C

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int wrong_key(void);
string key_check(string argv[], int n, string key);
string encrypt(string user_input, string key, int n);
int main(int argc, string argv[])
{
string key = NULL;
int n = 0;
//check if user used correct number of arguments
if (argc == 2)
{
key = argv[1];
n = strlen(key);
//check correctness of key and returns it back in uppercase
key = key_check(argv, n, key);
}
else
{
wrong_key();
}
string user_input = get_string("plaintext:");
string encrypted_string = encrypt(user_input, key, n);
printf("ciphertext: %s\n", encrypted_string);
}
//give user hint that he used wrong arguments,exit and return error code
int wrong_key(void)
{
printf("Usage: ./substition key \n");
printf("Key must containt 26 unique alphabetical characters. \n");
exit(1);
}
string key_check(string argv[], int n, string key)
{
//check if the key has 26 characters
if (n != 26)
{
wrong_key();
}
//check if each character in key is alphabetical character and convert all to uppercase
for (int i = 0; i < n; i++)
{
if ((key[i] >= 'a' && key[i] <= 'z') || (key[i] >= 'A' && key[i] <= 'Z'))
{
key[i] = toupper(key[i]);
}
else
{
wrong_key();
}
//check if character is not duplicated inside key
for (int j = 0; j < i; j++)
{
if (key[i] == key[j])
{
wrong_key();
}
}
}
return key;
}
string encrypt(string user_input, string key, int n)
{
//check user input length, create encrypted_string and copy user input inside
int user_length = strlen(user_input);
string encrypted_string = user_input;
//iterate over each char in user input and check if it's a letter
for (int i = 0; i < user_length; i++)
{
//if letter is found, substract ascii value for "a" to get letter position in key, encrypt this letter in encrypted string
if (user_input[i] >= 'a' && user_input[i] <= 'z')
{
int j = user_input[i] - 97;
//we use tolower to keep correct uppercase and lowercase as inputed by user
encrypted_string[i] = tolower(key[j]);
}
//if letter is found, substract ascii value for "A" to get letter position in key, encrypt this letter in encrypted string
else if (user_input[i] >= 'A' && user_input[i] <= 'Z')
{
int j = user_input[i] - 65;
encrypted_string[i] = key[j];
}
}
return encrypted_string;
}