-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_set2b.c
104 lines (82 loc) · 2.12 KB
/
problem_set2b.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
int valid_key(int argc, string argv[]); //checks if input is valid
string cipher(string text, string key); //encrypts text using substitution cipher
char cipher_char(char c, string key); //encrypts single character using substitution cipher
int main(int argc, string argv[])
{
int valid = valid_key(argc, argv);
if (valid != 0)
{
return valid;
}
string key = argv[1];
string plaintext = get_string("plaintext: ");
string ciphertext = cipher(plaintext, key);
printf("ciphertext: %s\n", ciphertext);
}
//checks if user inputs is valid
int valid_key(int argc, string argv[])
{
//check one and only one key has been inputted
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
string key = argv[1];
int length = strlen(key);
//check length of key
if (length != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
//check there are only alphabetical characters
for (int i = 0; i < length; i++)
{
if (!(isalpha(key[i])))
{
printf("Key must only contain letters.\n");
return 1;
}
}
//check no repeating characters
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j < length; j++)
{
if (tolower(key[i]) == tolower(key[j]))
{
printf("Key must not contain any repeating letters.\n");
return 1;
}
}
}
return 0;
}
//encrypts text using substitution cipher
string cipher(string text, string key)
{
int length = strlen(text);
for (int i = 0; i < length; i++)
{
text[i] = cipher_char(text[i], key);
}
return text;
}
//encrypts single character using substitution cipher
char cipher_char(char c, string key)
{
if (isupper(c))
{
c = toupper(key[(int) c - 65]); //A is 65 in ascii, so subtract 65.
}
if (islower(c))
{
c = tolower(key[(int) c - 97]); //a is 97 in ascii, so subtract 97.
}
return c;
}