-
Notifications
You must be signed in to change notification settings - Fork 10
/
(week2) - vigenere.c
122 lines (95 loc) · 2.92 KB
/
(week2) - vigenere.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// only accepts 1 arguments
if (argc != 2)
{
printf("Usage ./vigenere keyword\n");
return 1;
}
else
{
// checks to see if each character is a letter
for (int i = 0, n = strlen(argv[1]) ; i < n; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Usage ./vigenere keyword\n");
return 1;
}
}
}
string keyword = argv[1];
int keywordLength = strlen(keyword);
// Changing keyword
for (int i = 0; i < keywordLength; i++)
{
if (keyword[i] >= 97 && keyword[i] <= 122)
{
keyword[i] = keyword[i] - 97;
}
else if (keyword[i] >= 65 && keyword[i] <= 90)
{
keyword[i] = keyword[i] - 65;
}
else
{
}
}
// get plaintext
string plaintext = get_string("plaintext: ");
int plaintextLength = strlen(plaintext);
int k = 0;
// iterating through plaintext
for (int j = 0; j < plaintextLength ; j++)
{
// leave !letters the same
if (!isalpha(plaintext[j]))
{
}
// Continue the rest here
else
{
// for repeating the K
if (k >= keywordLength)
{
k = 0;
if (islower(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[k]) - 97) % 26) + 97;
}
else if (isupper(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[k]) - 65) % 26) + 65;
}
k++;
}
// for repeating the keyword
else if (j >= keywordLength)
{
if (islower(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[k]) - 97) % 26) + 97;
}
else if (isupper(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[k]) - 65) % 26) + 65;
}
k++;
}
// if keyword is long enough
else if (islower(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[j]) - 97) % 26) + 97;
}
else if (isupper(plaintext[j]))
{
plaintext[j] = (((plaintext[j] + keyword[j]) - 65) % 26) + 65;
}
}
}
printf("ciphertext: %s\n", plaintext);
}