/
atbash.cpp
104 lines (97 loc) · 2.65 KB
/
atbash.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
95
96
97
98
99
100
101
102
103
104
/**
Atbash cipher C++ implementation.
@file atbash.cpp
@author Devansh Singh
Chirag Tyagi
@brief Atbash cipher is a substitution cipher where all the letters are
reversed in order.
@date 01/03/2022
*/
#include <cctype>
#include "atbash.hpp"
/**
Default constructor for the AtbashCipher class.
*/
AtbashCipher::AtbashCipher() {
is_file = false;
create_dict();
}
/**
Parameterized constructor for the Atbash cipher class.
@param data Data to encrypt/decrypt.
@param is_file Read/Write from a file. Defaults to false.
*/
AtbashCipher::AtbashCipher(std::string data, bool is_file) {
if(is_file) {
file_path = data;
this->is_file = true;
}else {
this->data = data;
this->is_file = false;
}
create_dict();
}
/**
Overload extraction (<<) operator for displaying data.
@param output Reference to output stream.
@param obj Reference to AtbashCipher object.
@returns Reference to output stream.
*/
std::ostream& operator<<(std::ostream &output, AtbashCipher &obj) {
output << obj.data;
return output;
}
/**
Overload insertion (>>) operator for taking data from user.
@param input Reference to input stream.
@param obj Reference to AtbashCipher object.
@returns Reference to input stream.
*/
std::istream& operator>>(std::istream &input, AtbashCipher &obj) {
std::getline(input, obj.data);
return input;
}
/**
Encrypt the plaintext.
@returns Encrypted ciphertext.
*/
std::string AtbashCipher::encrypt() {
if(is_file){
FileIO file(file_path);
data = file.read();
}
for(int index = 0; index < data.length(); index++) {
if(data[index] >= 'A' && data[index] <= 'Z') {
data[index] = dict[data[index]];
}else if(data[index] >= 'a' && data[index] <= 'z') {
data[index] = std::tolower(dict[std::toupper(data[index])]);
}
}
if(is_file) {
FileIO file(file_path);
return (file.write(data) == true ? "0" : "1");
}
return data;
}
/**
Decrypt the ciphertext.
@returns Decrypted plaintext.
*/
std::string AtbashCipher::decrypt() {
if(is_file){
FileIO file(file_path);
data = file.read();
}
for(int index = 0; index < data.length(); index++) {
if(data[index] >= 'A' && data[index] <= 'Z') {
data[index] = dict[data[index]];
}else if(data[index] >= 'a' && data[index] <= 'z') {
data[index] = std::tolower(dict[std::toupper(data[index])]);
}
}
if(is_file) {
FileIO file(file_path);
return (file.write(data) == true ? "0" : "1");
}
return data;
}