-
Notifications
You must be signed in to change notification settings - Fork 8
/
caesars-cipher.cpp
60 lines (57 loc) · 1.25 KB
/
caesars-cipher.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
#include <bits/stdc++.h>
using namespace std;
string encrypt(string text, char s)
{
string result = "";
if(s>=65 && s<=90)
s=s-65+1;
else
s=s-97+1;
s=(int)s;
for (int i=0;i<text.length();i++)
{
if(text[i]==' ')
result+=" ";
else if (text[i]>=65 && text[i]<=90)
result += char(int(text[i]+s-65)%26 +65);
else
result += char(int(text[i]+s-97)%26 +97);
}
return result;
}
string decrypt(string st, char s)
{
string re = "";
if(s>=65 && s<=90)
s=s-65+1;
else
s=s-97+1;
s=(int)s;
s=26-s;
for (int i=0;i<st.length();i++)
{
if(st[i]==' ')
re+=" ";
else if (st[i]>=65 && st[i]<=90)
re += char(int(st[i]+(s-65))%26 +65);
else
re += char(int(st[i]+(s-97))%26 +97);
}
return re;
}
int main()
{
cout<<"Enter text to encrypt:"<<endl;
string text;
getline(cin,text);
cout<<"Enter key"<<endl;
char s;
cin>>s;
cout << "Plain Text: " << text<<endl;
cout << "Key: " << s<<endl;
string st=encrypt(text, s);
cout << "Cipher text: " << st<<endl;
string dt=decrypt(st,s);
cout << "Decrypted text: "<<dt<<endl;
return 0;
}