-
Notifications
You must be signed in to change notification settings - Fork 0
/
vignere.cpp
94 lines (79 loc) · 2.93 KB
/
vignere.cpp
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
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function to encrypt plaintext using Vigenère cipher
string encrypt(string plaintext, string keyword) {
string ciphertext = "";
int keyIndex = 0;
for (int i = 0; i < plaintext.length(); ++i) {
char currentChar = plaintext[i];
// Only encrypt alphabetic characters
if (isalpha(currentChar)) {
char keyChar = tolower(keyword[keyIndex % keyword.length()]);
int shift = keyChar - 'a'; // Shift based on keyword character
char encryptedChar;
// Encrypt uppercase characters
if (isupper(currentChar)) {
encryptedChar = ((currentChar - 'A' + shift) % 26) + 'A';
}
// Encrypt lowercase characters
else {
encryptedChar = ((currentChar - 'a' + shift) % 26) + 'a';
}
ciphertext += encryptedChar;
keyIndex++; // Move to the next letter of the keyword
} else {
// If non-alphabet character, add it as-is
ciphertext += currentChar;
}
}
return ciphertext;
}
// Function to decrypt ciphertext using Vigenère cipher
string decrypt(string ciphertext, string keyword) {
string plaintext = "";
int keyIndex = 0;
for (int i = 0; i < ciphertext.length(); ++i) {
char currentChar = ciphertext[i];
// Only decrypt alphabetic characters
if (isalpha(currentChar)) {
char keyChar = tolower(keyword[keyIndex % keyword.length()]);
int shift = keyChar - 'a'; // Shift based on keyword character
char decryptedChar;
// Decrypt uppercase characters
if (isupper(currentChar)) {
decryptedChar = ((currentChar - 'A' - shift + 26) % 26) + 'A';
}
// Decrypt lowercase characters
else {
decryptedChar = ((currentChar - 'a' - shift + 26) % 26) + 'a';
}
plaintext += decryptedChar;
keyIndex++; // Move to the next letter of the keyword
} else {
// If non-alphabet character, add it as-is
plaintext += currentChar;
}
}
return plaintext;
}
int main() {
string plaintext, keyword;
// Input the plaintext and the keyword
cout << "Enter the plaintext: ";
getline(cin, plaintext);
cout << "Enter the keyword: ";
getline(cin, keyword);
// Ensure keyword is all alphabetic
for (char &c : keyword) {
c = tolower(c);
}
// Encrypt the plaintext
string encryptedText = encrypt(plaintext, keyword);
cout << "Encrypted Text: " << encryptedText << endl;
// Decrypt the ciphertext
string decryptedText = decrypt(encryptedText, keyword);
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}