-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstitution.c
102 lines (84 loc) · 2.28 KB
/
substitution.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
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool is_valid_key(string key);
string encrypt(string plaintext, string key);
int main(int argc, string argv[])
{
// Check if there is exactly one command-line argument
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
// Get the key from the command-line argument
string key = argv[1];
// Check if the key is valid
if (!is_valid_key(key))
{
printf("Key must contain 26 characters.\n");
return 1;
}
// Get plaintext input from the user
string plaintext = get_string("plaintext: ");
// Encrypt the plaintext and print the result
string ciphertext = encrypt(plaintext, key);
printf("ciphertext: %s\n", ciphertext);
return 0;
}
bool is_valid_key(string key)
{
// Check if the key has exactly 26 characters
if (strlen(key) != 26)
{
return false;
}
// Create an array to keep track of characters
bool found[26] = {false};
// Iterate through each character in the key
for (int i = 0, n = strlen(key); i < n; i++)
{
// Check if the character is alphabetic
if (!isalpha(key[i]))
{
return false;
}
// Convert the character to uppercase
char c = toupper(key[i]);
// Check if the character has been seen before
if (found[c - 'A'])
{
return false;
}
// Mark the character as seen
found[c - 'A'] = true;
}
return true;
}
string encrypt(string plaintext, string key)
{
// Create a mapping of the alphabet to the key
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string ciphertext = plaintext;
// Iterate through each character in the plaintext
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
char c = plaintext[i];
// Determine whether the character is uppercase or lowercase
if (isupper(c))
{
ciphertext[i] = toupper(key[c - 'A']);
}
else if (islower(c))
{
ciphertext[i] = tolower(key[c - 'a']);
}
else
{
// Non-alphabetical characters are not encrypted
ciphertext[i] = c;
}
}
return ciphertext;
}