-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.cpp
More file actions
297 lines (255 loc) · 9.74 KB
/
Copy pathDatabase.cpp
File metadata and controls
297 lines (255 loc) · 9.74 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#include <filesystem>
#include <utility>
#include <fstream>
#include "Database.h"
#include <iterator>
#include <chrono>
#define DEBUG_ENCRYPTION_MANAGER 0
#define LOG_READ_VALUES 0
#define LOG_WRITE_VALUES 0
#if LOG_READ_VALUES == 1 || LOG_WRITE_VALUES == 1 || DEBUG_ENCRYPTION_MANAGER == 1
#include <iostream>
#endif
using std::ifstream, std::shared_ptr, std::ofstream, std::unique_ptr;
Database::Database(fs::path path, string password) {
this->path = path;
this->password = password;
}
#if LOG_WRITE_VALUES == 1 || LOG_READ_VALUES == 1
void printSharedPtr(shared_ptr<unsigned char[]> ptr, int size) {
std::cout << std::hex;
for (int i = 0; i < size; ++i) {
std::cout << (int)ptr.get()[i];
}
std::cout << std::dec << std::endl;
}
#endif
void Database::load() {
categories.clear();
entries.clear();
// open file in binary mode
ifstream file(this->path, std::ios::binary);
// stop eating new lines
file.unsetf(std::ios::skipws);
// read database password salt
shared_ptr<unsigned char[]> salt(new unsigned char[EncryptionManager::KEY_SIZE]);
file.read((char*)salt.get(), EncryptionManager::KEY_SIZE);
#if LOG_READ_VALUES == 1
std::cout << "Read salt:\n";
printSharedPtr(salt, EncryptionManager::KEY_SIZE);
#endif
// read initialization vector
shared_ptr<unsigned char[]> initializationVector(new unsigned char[EncryptionManager::BLOCK_SIZE]);
file.read((char*)initializationVector.get(), EncryptionManager::BLOCK_SIZE);
#if LOG_READ_VALUES == 1
std::cout << "Read init vector:\n";
printSharedPtr(initializationVector, EncryptionManager::BLOCK_SIZE);
#endif
if (this->encryptionManager == nullptr) {
this->encryptionManager = std::make_unique<EncryptionManager>(salt, initializationVector, password);
#if DEBUG_ENCRYPTION_MANAGER == 1
std::cout << "Created encryption manager for reading\n";
#endif
}
// read timestamp
// shared_ptr<unsigned char[]> timestamp(new unsigned char[sizeof(long)]);
// file.read((char*)initializationVector.get(), sizeof(long));
// this->lastReadTimestamp = *((long*)timestamp.get());
long* timestamp = new long;
file.read((char*)timestamp, sizeof(long));
lastReadTimestamp = *timestamp;
delete timestamp;
#if LOG_READ_VALUES == 1
std::cout << "Read timestamp: " << lastReadTimestamp << std::endl;
#endif
// read size of entries
unique_ptr<char[]> sizeBuffer(new char[sizeof(unsigned long)]);
file.read(sizeBuffer.get(), sizeof(unsigned long));
unsigned long size = *((long*)sizeBuffer.get());
#if LOG_READ_VALUES == 1
std::cout << "Size of password entries: " << size << std::endl;
#endif
// allocate memory for entries
vector<unsigned char> bytes(size);
// read and decrypt entries
file.read((char*)&bytes[0], size);
#if LOG_READ_VALUES == 1
std::cout << "Size of read entries: " << bytes.size() << std::endl;
#endif
this->encryptionManager->decrypt(bytes);
char* rangeFromPointer = (char*)&bytes[0];
for (int i = 0; i < bytes.size(); ++i) {
char* ptr = (char*)&bytes[0] + i;
if (*ptr == '\n') {
auto distance = ptr - rangeFromPointer;
string formattedEntry(rangeFromPointer, distance);
rangeFromPointer = ptr + 1; // skip current delimiter
PasswordEntry passwordEntry(formattedEntry);
entries.push_back(passwordEntry);
}
}
bytes.clear();
unsigned char temp;
while (file >> temp) {
bytes.push_back(temp);
}
#if LOG_READ_VALUES == 1
std::cout << "Size of read categories: " << bytes.size() << std::endl;
#endif
this->encryptionManager->decrypt(bytes);
#if LOG_READ_VALUES == 1
std::cout << "Size of read categories after decryption: " << bytes.size() << std::endl;
#endif
rangeFromPointer = (char*)bytes.data();
for (int i = 0; i < bytes.size(); ++i) {
char* ptr = (char*)bytes.data() + i;
if (*ptr == '\n') {
auto distance = ptr - rangeFromPointer; // -1 to skip the delimiter
string category(rangeFromPointer, distance);
#if LOG_READ_VALUES == 1
std::cout << "Read category: " << category << std::endl;
#endif
categories.push_back(category);
rangeFromPointer = ptr + 1;
}
}
}
void Database::save() {
ofstream file(this->path, std::ios::out | std::ios::binary);
// create encryption manager if it wasn't created before
// generate salt and initialization vector
if (this->encryptionManager == nullptr) {
shared_ptr<unsigned char[]> salt(new unsigned char[EncryptionManager::SALT_SIZE]);
for (int i = 0; i < EncryptionManager::SALT_SIZE; ++i) {
salt[i] = (unsigned char) rand();
}
shared_ptr<unsigned char[]> initializationVector(new unsigned char[EncryptionManager::BLOCK_SIZE]);
for (int i = 0; i < EncryptionManager::BLOCK_SIZE; ++i) {
salt[i] = (unsigned char) rand();
}
this->encryptionManager = std::make_unique<EncryptionManager>(salt, initializationVector, password);
#if DEBUG_ENCRYPTION_MANAGER == 1
std::cout << "Created encryption manager for saving\n";
#endif
}
// write salt
shared_ptr<unsigned char[]> salt = this->encryptionManager->salt;
file.write((char*)salt.get(), EncryptionManager::SALT_SIZE);
#if LOG_WRITE_VALUES == 1
std::cout << "Written salt:\n";
printSharedPtr(salt, EncryptionManager::SALT_SIZE);
#endif
// write initialization vector
shared_ptr<unsigned char[]> initializationVector = this->encryptionManager->initializationVector;
file.write((char*)initializationVector.get(), EncryptionManager::BLOCK_SIZE);
#if LOG_WRITE_VALUES == 1
std::cout << "Written init vector:\n";
printSharedPtr(initializationVector, EncryptionManager::BLOCK_SIZE);
#endif
// write timestamp
const auto now = std::chrono::system_clock::now();
long timestamp = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
file.write((char*)×tamp, sizeof(long));
#if LOG_WRITE_VALUES == 1
std::cout << "Written timestamp: " << timestamp << std::endl;
#endif
// encrypt and write entries
vector<unsigned char> bytes;
for (int i = 0; i < entries.size(); ++i) {
const string formattedEntry = entries[i].getFormattedEntry();
for (int j = 0; j < formattedEntry.length(); ++j) {
bytes.push_back((unsigned char)formattedEntry.c_str()[j]);
}
bytes.push_back((unsigned char)'\n');
}
this->encryptionManager->encrypt(bytes);
unsigned long size = bytes.size();
#if LOG_WRITE_VALUES == 1
std::cout << "Written size of entries: " << size << std::endl;
#endif
file.write((char*)&size, sizeof(unsigned long)); // write size of the encrypted entries
file.write((char*)bytes.data(), bytes.size());
// encrypt and write categories
bytes.clear();
for (int i = 0; i < categories.size(); ++i) {
for (int j = 0; j < categories[i].length(); ++j) {
bytes.push_back((unsigned char)categories[i].c_str()[j]);
}
bytes.push_back((unsigned char)'\n');
}
this->encryptionManager->encrypt(bytes);
#if LOG_WRITE_VALUES == 1
std::cout << "Size of written categories: " << bytes.size() << "\n";
#endif
file.write((char*)bytes.data(), bytes.size());
}
void Database::addPassword(const PasswordEntry& entry) {
if (entries.empty() || std::find(entries.begin(), entries.end(), entry) == entries.end()) {
bool categoryExists = false;
for (int i = 0; i < categories.size(); ++i) {
if (categories[i] == entry.getCategory()) {
categoryExists = true;
break;
}
}
if (!categoryExists) {
throw std::runtime_error("Tried to add a password to a category that doesn't exist");
}
needsSaving = true;
entries.push_back(entry);
} else {
throw std::runtime_error("Tried to add a password that already exists");
}
}
void Database::addCategory(string &category) {
if (categories.empty() || std::find(categories.begin(), categories.end(), category) == categories.end()) {
needsSaving = true;
categories.push_back(category);
} else {
string message = "Tried to add category that already exists: [" + category + "]";
throw std::runtime_error(message);
}
}
vector<PasswordEntry> Database::getPasswords() {
return this->entries;
}
vector<string> Database::getCategories() {
return this->categories;
}
void Database::editPassword(const int& entryIndex, const PasswordEntry &newEntry) {
if (entryIndex >= 0 && entryIndex < entries.size()) {
entries[entryIndex] = newEntry;
needsSaving = true;
} else {
throw std::runtime_error("Invalid entry index");
}
}
void Database::deletePassword(const int& entryIndex) {
if (entryIndex >= 0 && entryIndex < entries.size()) {
needsSaving = true;
entries.erase(entries.begin() + entryIndex);
} else {
throw std::runtime_error("Invalid entry index");
}
}
void Database::deleteCategoryAndItsPasswords(const int& categoryIndex) {
if (categoryIndex < 0 || categoryIndex >= categories.size()) {
throw std::runtime_error("Invalid category index");
}
needsSaving = true;
string category = categories[categoryIndex];
categories.erase(categories.begin() + categoryIndex);
vector<int> entriesToDelete;
for (int i = 0; i < entries.size(); ++i) {
PasswordEntry entry = entries[i];
if (entry.getCategory() == category) {
entriesToDelete.push_back(i);
}
}
for (int i = 0; i < entriesToDelete.size(); ++i) {
deletePassword(entriesToDelete[i]);
}
}
bool Database::getNeedsSaving() {
return this->needsSaving;
}