-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCeasar.cpp
93 lines (71 loc) · 2.5 KB
/
Ceasar.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
#include <iostream>
using namespace std;
//we'll be using ASCII in this
int main()
{
int choice;
cout << "1. Encryption" << endl << "2. Decryption" << endl << "Enter choice(1,2): ";
cin >> choice;
cin.ignore();
if (choice == 1){
// encryption
string msg;
cout << "Message can only be alphabetic" << endl;
cout << "Enter message: ";
getline(cin, msg);
int key;
cout << "Enter key (0-25): ";
cin >> key;
cin.ignore();
string encryptedText = msg;
for (int i = 0; i < msg.size(); i ++){
if(msg[i]==32){
continue; //32 is ASCII of space character, we will ignore it
} else {
if((msg[i]+key) > 122) {
//after lowercase z move back to a, z's ASCII is 122
int temp = (msg[i] + key) - 122;
encryptedText[i] = 96 + temp;
} else if (msg[i] + key > 90 && msg[i] <= 96){
//after uppercase Z move back to A, 90 is Z's ASCII
int temp = (msg[i] + key) - 90;
encryptedText[i] = 64 + temp;
} else {
//in case of characters being in between A-Z & a-z
encryptedText[i] += key;
}
} //if
} // for
cout << "Encrypted Message: " << encryptedText;
} else if (choice == 2){
//decryption
string encpMsg;
cout << "Message can only be alphabetic" << endl;
cout << "Enter encrypted text: ";
getline(cin, encpMsg);
int dcyptKey;
cout << "Enter key (0-25): ";
cin >> dcyptKey;
cin.ignore();
string decryptedText = encpMsg;
for (int i = 0; i < encpMsg.size(); i++){
if(encpMsg[i]==32){
continue; //ignoring space
} else {
if((encpMsg[i] - dcyptKey) < 97 && (encpMsg[i] - dcyptKey) > 90){
int temp = (encpMsg[i] - dcyptKey) + 26;
decryptedText[i] = temp;
} else if((encpMsg[i] - dcyptKey) < 65){
int temp = (encpMsg[i] - dcyptKey) + 26;
decryptedText[i] = temp;
} else {
decryptedText[i] = encpMsg[i] - dcyptKey;
}
}
}
cout << "Decrypted Message: " << decryptedText << endl;
} else {
cout << "Invalid choice";
}
return 0;
}