Repository navigation
Expand file tree
/
Copy pathcryptographicagent.cpp
More file actions
422 lines (336 loc) 路 13.3 KB
/
Copy pathcryptographicagent.cpp
File metadata and controls
422 lines (336 loc) 路 13.3 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#include "cryptographicagent.h"
#include "ui_cryptographicagent.h"
cryptographicAgent::cryptographicAgent(QWidget *parent)
: QWidget(parent)
, ui(new Ui::cryptographicAgent)
{
ui->setupUi(this);
this->hide();
}
cryptographicAgent::~cryptographicAgent()
{
delete ui;
}
void cryptographicAgent::storePassword(QString pass) {
strncpy(password, pass.toStdString().c_str() , sizeof(password) - 1);
qDebug() << "Password stored in memory.";
// Schedule secureErase() to run in 5 minutes (300,000 ms)
QTimer::singleShot(300000, [=]() { secureErase(password, sizeof(password)); });
hasPassword=true;
}
void cryptographicAgent::secureErase(char* buffer, size_t size) {
volatile char* p = buffer;
while (size--) {
*p++ = 0;
}
qDebug() << "Session timed out, Password securely erased.";
hasPassword=false;
}
QString cryptographicAgent::getAppDataFilePath(const QString& filename) {
QString appDataPath;
#ifdef _WIN32
appDataPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/KCATDVWSPJD";
#elif defined(__APPLE__)
appDataPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/KCATDVWSPJD";
#else
appDataPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/KCATDVWSPJD";
#endif
// Ensure filename is safe (no directory traversal)
QString safeFilename = QFileInfo(filename).fileName();
// Construct full path
QString fullPath = QDir::cleanPath(appDataPath + "/" + safeFilename);
qDebug()<<"File path before repair: "<<fullPath;
// Replace "Local" with "Roaming" to get the correct path
fullPath.replace("Local", "Roaming");
qDebug() << "Corrected AppDataPath:" << appDataPath;
// Ensure compatibility with OpenSSL (use forward slashes)
return QDir::toNativeSeparators(fullPath);
}
QString cryptographicAgent::decryptFileToString(const QString &filePath, const QByteArray &key, const QByteArray &iv) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
throw std::runtime_error("Failed to open encrypted file.");
}
// OpenSSL decryption context
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("Failed to create OpenSSL context.");
}
if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr,
reinterpret_cast<const unsigned char *>(key.data()),
reinterpret_cast<const unsigned char *>(iv.data()))) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Failed to initialize decryption.");
}
QByteArray encryptedData;
QByteArray buffer(4096, 0);
while (!file.atEnd()) {
qint64 bytesRead = file.read(buffer.data(), buffer.size());
if (bytesRead > 0) {
encryptedData.append(buffer.left(bytesRead));
} else if (bytesRead < 0) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Error reading encrypted file.");
}
}
file.close();
// Perform decryption
QByteArray decryptedData(encryptedData.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc()), 0);
int decryptedLength = 0;
int finalLength = 0;
if (!EVP_DecryptUpdate(ctx, reinterpret_cast<unsigned char *>(decryptedData.data()), &decryptedLength,
reinterpret_cast<const unsigned char *>(encryptedData.data()), encryptedData.size())) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Error during decryption.");
}
if (!EVP_DecryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(decryptedData.data()) + decryptedLength, &finalLength)) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Error finalizing decryption. Wrong key/IV?");
}
EVP_CIPHER_CTX_free(ctx);
decryptedData.resize(decryptedLength + finalLength);
return QString::fromUtf8(decryptedData);
}
// Derive encryption key and IV from password
bool cryptographicAgent::deriveKeyAndIV(const QString &password, QByteArray &key, QByteArray &iv) {
key.resize(32); // 256-bit key
iv.resize(16); // 128-bit IV
QByteArray salt = QByteArray::fromStdString(usrnam_salt);/*"example_salt"*/; // You can generate a random salt for stronger security
// qDebug() << "usrnam_salt (std::string):" << QString::fromStdString(usrnam_salt);
// qDebug() << "usrnam_salt size:" << usrnam_salt.size();
// qDebug() << "Salt size:" << salt.size() << "Salt data:" << salt.toHex();
// Use PBKDF2 to derive the key and IV
if (!PKCS5_PBKDF2_HMAC(password.toUtf8().data(),
password.length(),
reinterpret_cast<const unsigned char*>(salt.data()), salt.size(),
10000, // Iteration count
EVP_sha256(),
key.size() + iv.size(),
reinterpret_cast<unsigned char*>(key.data()))) {
qWarning() << "Failed to derive key/IV.";
return false;
}
iv = key.mid(32, 16); // Extract the last 16 bytes as IV
key = key.left(32); // First 32 bytes as the key
return true;
}
void cryptographicAgent::encryptStringToFile(const QString &data, const QString &filePath, const QByteArray &key, const QByteArray &iv) {
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly)) {
throw std::runtime_error("Failed to open file for writing.");
}
// OpenSSL encryption context
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error("Failed to create OpenSSL context.");
}
if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr,
reinterpret_cast<const unsigned char *>(key.data()),
reinterpret_cast<const unsigned char *>(iv.data()))) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Failed to initialize encryption.");
}
QByteArray inputData = data.toUtf8();
QByteArray encryptedData(inputData.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc()), 0);
int encryptedLength = 0;
int finalLength = 0;
// Perform encryption
if (!EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char *>(encryptedData.data()), &encryptedLength,
reinterpret_cast<const unsigned char *>(inputData.data()), inputData.size())) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Error during encryption.");
}
if (!EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(encryptedData.data()) + encryptedLength, &finalLength)) {
EVP_CIPHER_CTX_free(ctx);
throw std::runtime_error("Error finalizing encryption.");
}
EVP_CIPHER_CTX_free(ctx);
encryptedData.resize(encryptedLength + finalLength);
// Write encrypted data to file
if (file.write(encryptedData) != encryptedData.size()) {
throw std::runtime_error("Failed to write encrypted data to file.");
}
file.close();
}
int cryptographicAgent::encryptToFile(QString fileName, QString data){
if (!hasPassword) {
QEventLoop loop;
connect(this, &cryptographicAgent::passwordSet, &loop, &QEventLoop::quit);
showUI(1);
loop.exec(); // Blocks execution until passwordSet() is emitted
}
QByteArray key, iv;
if (!deriveKeyAndIV(password, key, iv)) {
QMessageBox::warning(this, "Error", "Failed to generate encryption key and IV.");
return -1;
}
QString dataToEncrypt = data;
if (dataToEncrypt.isEmpty()) {
QMessageBox::warning(this, "Error", "No content to encrypt.");
return -2;
}
QString filePath = getAppDataFilePath(fileName);
qDebug()<<"the filepath that was generated: "<<filePath;
try {
encryptStringToFile(dataToEncrypt, filePath, key, iv);
//QMessageBox::information(this, "Success", "File encrypted successfully.");
} catch (const std::runtime_error &e) {
QMessageBox::warning(this, "Error", e.what());
return -3;
}
return 0;
}
QString cryptographicAgent::decryptFromFile(QString fileName)
{
if (!hasPassword) {
QEventLoop loop;
connect(this, &cryptographicAgent::passwordSet, &loop, &QEventLoop::quit);
showUI(1);
loop.exec(); // Blocks execution until passwordSet() is emitted
}
QString decryptedContent="";
QByteArray key, iv;
if (!deriveKeyAndIV(password, key, iv)) {
QMessageBox::warning(this, "Error", "Failed to generate decryption key and IV.");
return QString();
}
QString filePath = getAppDataFilePath(fileName);
try {
decryptedContent = decryptFileToString(filePath, key, iv);
// ui->FileContents->setPlainText(decryptedContent); // Display decrypted content
//QMessageBox::information(this, "Success", "File decrypted successfully. CONTENTS:"+decryptedContent);
} catch (const std::runtime_error &e) {
QMessageBox::warning(this, "Error", e.what());
}
return decryptedContent;
}
std::string cryptographicAgent::setPassFirstTime()
{
firstTime=true;
showUI(2);
QEventLoop loop;
connect(this, &cryptographicAgent::passwordSet, &loop, &QEventLoop::quit);
loop.exec();
return hashResult=hashPassword(ui->passwordField->text()).toStdString();
}
QString cryptographicAgent::hashPassword(const QString& pass){
return QString(QCryptographicHash::hash(pass.toUtf8(), QCryptographicHash::Sha256).toHex()) ;
}
void cryptographicAgent::showUI(int mode){
// connect(ui->cofirmButton, &QPushButton::clicked, this, [&]() {
// // Notify that password is set
// // this->hide(); // Close UI
// });
ui->passwordConfirmField->clear();
ui->passwordField->clear();
switch (mode) {
case 1: //for normal operation
ui->confrimPassText->hide();
ui->passwordConfirmField->hide();
this->show();
break;
case 2: //for setting a new password
ui->confrimPassText->show();
ui->passwordConfirmField->show();
this->show();
break;
default:
break;
}
}
void cryptographicAgent::on_cofirmButton_clicked()
{
emit confirmButtonClicked();
QString pass=ui->passwordField->text();
if( !ui->passwordConfirmField->isHidden() ){
if(ui->passwordField->text() != ui->passwordConfirmField->text() ){
QMessageBox::warning(this, "Error", "Passwords do not match!!");
return;
}
}
if(firstTime){
storePassword( ui->passwordField->text() );
this->hide();
return;
}
else if( hashResult != hashPassword(pass).toStdString() ){ //CRITIAL password hash verification
QMessageBox::warning(this, "Error", "Wrong Password!!");
return;
}
else{
storePassword( ui->passwordField->text() );
emit passwordSet();
this->hide();
}
}
void cryptographicAgent::setHash(std::string str){
hashResult=str;
}
std::string cryptographicAgent::getHash(){
return hashResult;
}
void cryptographicAgent::closeEvent(QCloseEvent *event) {
emit windowClosed();
event->accept(); // Accept the close event
}
/// @brief
/// @return
bool cryptographicAgent::authenticate(){
showUI(1);
bool ok = false;
// Create an event loop to halt execution
QEventLoop loop;
// Connect a signal (e.g., button clicked) to exit the loop when the user provides input
// connect(ui->cofirmButton, &QPushButton::clicked, &loop, &QEventLoop::quit);
connect(this, &cryptographicAgent::confirmButtonClicked, &loop, &QEventLoop::quit);
// Connect window close to exit loop
connect(this, &cryptographicAgent::windowClosed, &loop, &QEventLoop::quit);// Run the event loop (halts execution here until quit() is called)
loop.exec();
// // Check if the window is still open (if closed, return false)
// if (!this->isVisible()) {
// qDebug()<<"manual window close detected";
// return false;
// }
this->hide();
QString pass = ui->passwordField->text();
if (hashPassword(pass).toStdString() == hashResult) {
ok = true;
}
return ok;
}
bool cryptographicAgent::authenticate(QString pass){
bool ok=false;
if (hashPassword(pass).toStdString() == hashResult) {
ok = true;
}
return ok;
}
void cryptographicAgent::on_passwordField_returnPressed()
{
on_cofirmButton_clicked();
}
void cryptographicAgent::on_passwordConfirmField_returnPressed()
{
on_cofirmButton_clicked();
}
void cryptographicAgent::tellUsename(std::string str){
usrnam_salt=str;
}
int cryptographicAgent::changePassword(const QString& oldPassword, const QString& newPassword)
{
// Verify if the old password is correct
if (hashPassword(oldPassword).toStdString() != hashResult) {
qWarning() << "Old password is incorrect.";
return -1;
}
if (newPassword.isEmpty()) {
qWarning() << "New password cannot be empty.";
return -2; // Return false if the new password is empty
}
qDebug()<<"the previous hash is: "<<hashResult<<"\nand the new hash is: "<<hashPassword(newPassword).toStdString();
hashResult = hashPassword(newPassword).toStdString();
secureErase(password, sizeof(password));
storePassword(newPassword);
qDebug() << "Password changed successfully.";
return 1; // Return true if the password change is successful
}