-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcaesarCipher.cpp
86 lines (79 loc) · 2.29 KB
/
caesarCipher.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
/*
* Implementation of caesar cipher in CPP
*
*/
#include<iostream>
#include<sstream>
const std::string encrypt ( const std::string plainText, int key )
{
std::stringstream cipherStream;
int x;
for ( auto &c : plainText ) {
x = c + key;
if ( c >= 'A' && c <= 'Z' ) {
x = ( x > 'Z') ? ( 'A' + (x - 1) - 'Z') : x ;
} else if ( c >= 'a' && c <= 'z' ) {
x = ( x > 'z') ? ( 'a' + (x - 1) - 'z') : x ;
}
cipherStream << char(x);
}
return cipherStream.str();
}
const std::string decrypt ( const std::string cipherText, int key )
{
std::stringstream plainStream;
int x;
for ( auto &c : cipherText ) {
x = c - key;
if ( c >= 'A' && c <= 'Z' ) {
x = ( x < 'A') ? ( 'Z' -('A'- (x + 1))) : x ;
} else if ( c >= 'a' && c <= 'z' ) {
x = ( x < 'a') ? ( 'z' - ('a' - (x + 1))) : x ;
}
plainStream << char(x);
}
return plainStream.str();
}
int main()
{
std::cout << "----Caesar Cipher ----\n"
<< "What would you like to do?\n"
<< "1. Encrypt a plain text\n"
<< "2. Decrypt a cipher text\n"
<< "Enter a choice:";
int choice, key;
std::string plainText, cipherText;
std::cin >> choice;
switch(choice) {
case 1 :
{
std::cout << "Enter plain text:";
std::cin >> plainText;
std::cout << "Enter key ( 1 - 25 ):";
std::cin >> key;
cipherText = encrypt(plainText, key);
std::cout << "Plain Text: " << plainText
<< " ---> "
<< "Cipher Text: " << cipherText
<< std::endl;
break;
}
case 2 :
{
std::cout << "Enter cipher text:";
std::cin >> cipherText;
std::cout << "Enter key ( 1 - 25 ):";
std::cin >> key;
plainText = decrypt(cipherText, key);
std::cout << "Cipher Text: " << cipherText
<< " ---> "
<< "Plain Text: " << plainText
<< std::endl;
break;
}
default:
std::cout << "Invalid Choice\n";
break;
}
return 0;
}