-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptor.cpp
More file actions
319 lines (273 loc) · 11.8 KB
/
Encryptor.cpp
File metadata and controls
319 lines (273 loc) · 11.8 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
#include "Encryptor.h"
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <filesystem>
#include <chrono>
#include <iostream>
#include <unordered_set>
#include <cstdlib>
// OpenSSL
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <cstring>
namespace fs = std::filesystem;
namespace EncryptionLib {
// ---------- فایل کمکی ----------
static bool readAll(std::ifstream& ifs, std::vector<char>& out) {
ifs.seekg(0, std::ios::end);
std::streampos sz = ifs.tellg();
ifs.seekg(0, std::ios::beg);
if (sz < 0) return false;
out.resize(static_cast<size_t>(sz));
ifs.read(out.data(), static_cast<std::streamsize>(out.size()));
return ifs.good();
}
static bool readFileToVector(const std::string &filePath, std::vector<char>& data) {
std::ifstream ifs(filePath, std::ios::binary);
if (!ifs) return false;
return readAll(ifs, data);
}
static bool writeVectorToFile(const std::string &filePath, const std::vector<char>& data) {
std::ofstream ofs(filePath, std::ios::binary);
if (!ofs) return false;
ofs.write(data.data(), static_cast<std::streamsize>(data.size()));
return ofs.good();
}
std::string Encryptor::getTempFilePath(const std::string &extension) {
auto now = std::chrono::high_resolution_clock::now().time_since_epoch().count();
fs::path p = fs::temp_directory_path() / ("enc_" + std::to_string(now) + extension);
return p.string();
}
// ---------- 7zip ----------
std::string Encryptor::createZipArchive(const std::string& inputPath, const std::string& zipPassword) {
std::string tempZipPath = getTempFilePath(".zip");
#if defined(_WIN32)
std::string redirect = " >nul 2>&1";
#else
std::string redirect = " >/dev/null 2>&1";
#endif
// zip با پسورد
// نکته: اگر میخواهید AES در zip باشد: -mem=AES256
std::string cmd = "7z a -tzip -p" + zipPassword + " \"" + tempZipPath + "\" \"" + inputPath + "\"" + redirect;
int ret = std::system(cmd.c_str());
if (ret != 0) return "";
return tempZipPath;
}
bool Encryptor::extractZipArchive(const std::string& archivePath, const std::string& zipPassword, const std::string& outputPath) {
fs::create_directories(outputPath);
#if defined(_WIN32)
std::string redirect = " >nul 2>&1";
#else
std::string redirect = " >/dev/null 2>&1";
#endif
std::string cmd = "7z x -tzip -p" + zipPassword + " \"" + archivePath + "\" -o\"" + outputPath + "\" -y" + redirect;
int ret = std::system(cmd.c_str());
return (ret == 0);
}
// ---------- Key ID (SHA-256 hex) ----------
static std::string toHex(const unsigned char* buf, size_t len) {
static const char* digits = "0123456789abcdef";
std::string s; s.resize(len * 2);
for (size_t i = 0; i < len; ++i) {
s[2*i] = digits[(buf[i] >> 4) & 0xF];
s[2*i+1] = digits[(buf[i] ) & 0xF];
}
return s;
}
std::string Encryptor::computeKeyIdHex(const std::string& key) {
unsigned char hash[SHA256_DIGEST_LENGTH];
// برای domain-separation میتوانید بهجای key، "kid:"+key را هش کنید
SHA256(reinterpret_cast<const unsigned char*>(key.data()), key.size(), hash);
return toHex(hash, SHA256_DIGEST_LENGTH);
}
// ---------- Header: ENCLIBv1 + KID:<hex> + خط خالی ----------
bool Encryptor::writeFileWithHeader(const std::string& outPath, const std::string& keyIdHex, const std::vector<char>& payload) {
std::ofstream ofs(outPath, std::ios::binary);
if (!ofs) return false;
ofs << "ENCLIBv1\n";
ofs << "KID:" << keyIdHex << "\n";
ofs << "\n"; // delimiter
ofs.write(payload.data(), static_cast<std::streamsize>(payload.size()));
return ofs.good();
}
bool Encryptor::readFileWithHeader(const std::string& inPath, std::string& keyIdHexOut, std::vector<char>& payloadOut) {
std::ifstream ifs(inPath, std::ios::binary);
if (!ifs) return false;
std::string line1;
if (!std::getline(ifs, line1)) return false;
if (line1 != "ENCLIBv1") return false;
std::string line2;
if (!std::getline(ifs, line2)) return false;
if (line2.rfind("KID:", 0) != 0) return false;
keyIdHexOut = line2.substr(4);
// خط خالی جداکننده
std::string empty;
if (!std::getline(ifs, empty)) return false;
// بقیه فایل = payload
payloadOut.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
return true;
}
// ---------- مدیریت فایل کلید ----------
bool Encryptor::loadKeysFile(const std::string& keysFilePath, std::vector<std::string>& keys) {
keys.clear();
std::ifstream f(keysFilePath);
if (!f) return false;
std::string line;
while (std::getline(f, line)) {
// حذف spaceهای ابتدا/انتها
size_t a = line.find_first_not_of(" \t\r\n");
size_t b = line.find_last_not_of(" \t\r\n");
if (a == std::string::npos || b == std::string::npos) continue;
std::string k = line.substr(a, b - a + 1);
if (!k.empty()) keys.push_back(k);
}
// حذف تکراریها بر اساس keyId
dedupeKeysById(keys);
return true;
}
void Encryptor::dedupeKeysById(std::vector<std::string>& keys) {
std::unordered_set<std::string> seen;
std::vector<std::string> out;
out.reserve(keys.size());
for (auto& k : keys) {
std::string id = computeKeyIdHex(k);
if (seen.insert(id).second) out.push_back(k);
}
keys.swap(out);
}
// حذف کلیدی که keyIdHex آن برابر است
size_t Encryptor::removeKeyById(const std::string& keysFilePath, const std::string& keyIdHex) {
std::vector<std::string> keys;
(void)loadKeysFile(keysFilePath, keys);
std::ofstream ofs(keysFilePath, std::ios::trunc);
size_t remain = 0;
for (auto& k : keys) {
if (computeKeyIdHex(k) == keyIdHex) continue; // حذف
ofs << k << "\n";
++remain;
}
return remain;
}
// ---------- Transform پیشفرض ----------
void Encryptor::defaultXorTransform(std::vector<char>& data, const std::string& key) {
if (key.empty()) return;
size_t n = data.size(), m = key.size();
for (size_t i = 0; i < n; ++i) data[i] ^= key[i % m];
}
// AES-256-CBC با IV صفر (فقط دمویی). برای تولید IV تصادفی و ذخیره آن در هدر اقدام کنید.
void Encryptor::defaultAesEncryptTransform(std::vector<char>& data, const std::string& key) {
unsigned char keyBytes[32] = {0};
unsigned char iv[16] = {0};
std::memcpy(keyBytes, key.data(), std::min<size_t>(key.size(), 32));
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return;
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, keyBytes, iv) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
int outLen = static_cast<int>(data.size()) + EVP_CIPHER_block_size(EVP_aes_256_cbc());
std::vector<char> out(outLen);
int n1 = 0, n2 = 0;
if (EVP_EncryptUpdate(ctx,
reinterpret_cast<unsigned char*>(out.data()), &n1,
reinterpret_cast<const unsigned char*>(data.data()), static_cast<int>(data.size())) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
if (EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char*>(out.data()) + n1, &n2) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
EVP_CIPHER_CTX_free(ctx);
out.resize(n1 + n2);
data.swap(out);
}
void Encryptor::defaultAesDecryptTransform(std::vector<char>& data, const std::string& key) {
unsigned char keyBytes[32] = {0};
unsigned char iv[16] = {0};
std::memcpy(keyBytes, key.data(), std::min<size_t>(key.size(), 32));
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) return;
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, keyBytes, iv) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
std::vector<char> out(data.size());
int n1 = 0, n2 = 0;
if (EVP_DecryptUpdate(ctx,
reinterpret_cast<unsigned char*>(out.data()), &n1,
reinterpret_cast<const unsigned char*>(data.data()), static_cast<int>(data.size())) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
if (EVP_DecryptFinal_ex(ctx, reinterpret_cast<unsigned char*>(out.data()) + n1, &n2) != 1) { EVP_CIPHER_CTX_free(ctx); return; }
EVP_CIPHER_CTX_free(ctx);
out.resize(n1 + n2);
data.swap(out);
}
// ---------- Encrypt ----------
OperationResult Encryptor::encrypt(const std::string& encryptedFilePath,
const std::string& keysFilePath,
const std::string& zipPassword,
const std::string& inputPath,
const std::vector<TransformAlgorithm>& transformAlgos) {
OperationResult result{false, "", 0};
// 1) ZIP
std::string tempZip = createZipArchive(inputPath, zipPassword);
if (tempZip.empty()) { result.message = "7zip archive failed."; return result; }
// 2) Keys
std::vector<std::string> keys;
if (!loadKeysFile(keysFilePath, keys) || keys.empty()) { result.message = "keys.txt not found or empty."; return result; }
std::string key = keys.front();
std::string keyIdHex = computeKeyIdHex(key);
// 3) Read zip as bytes
std::vector<char> data;
if (!readFileToVector(tempZip, data)) { result.message = "cannot read temp zip."; fs::remove(tempZip); return result; }
// 4) Apply transforms in order
for (const auto& algo : transformAlgos) algo.encrypt(data, key);
// 5) Write HEADER + payload
if (!writeFileWithHeader(encryptedFilePath, keyIdHex, data)) {
result.message = "cannot write encrypted file."; fs::remove(tempZip); return result;
}
// 6) Remove used key locally (one-time usage policy)
size_t remaining = removeKeyById(keysFilePath, keyIdHex);
fs::remove(tempZip);
result.success = true;
result.remainingKeys = remaining;
result.message = "Encryption OK. KID=" + keyIdHex + " -> " + encryptedFilePath;
return result;
}
// ---------- Decrypt ----------
OperationResult Encryptor::decrypt(const std::string& outputPath,
const std::string& keysFilePath,
const std::string& zipPassword,
const std::string& encryptedFilePath,
const std::vector<TransformAlgorithm>& transformAlgos) {
OperationResult result{false, "", 0};
// 1) Read header + payload
std::string keyIdHex;
std::vector<char> payload;
if (!readFileWithHeader(encryptedFilePath, keyIdHex, payload)) {
result.message = "Invalid encrypted file header (ENCLIBv1/KID).";
return result;
}
// 2) Load keys and find matching key by ID
std::vector<std::string> keys;
if (!loadKeysFile(keysFilePath, keys) || keys.empty()) { result.message = "keys.txt not found or empty."; return result; }
std::string matchedKey;
for (auto& k : keys) {
if (computeKeyIdHex(k) == keyIdHex) { matchedKey = k; break; }
}
if (matchedKey.empty()) {
result.message = "No matching key for KID=" + keyIdHex;
return result;
}
// 3) Apply transforms in reverse
for (auto it = transformAlgos.rbegin(); it != transformAlgos.rend(); ++it) {
it->decrypt(payload, matchedKey);
}
// 4) Write temp zip and extract
std::string tempZip = getTempFilePath(".zip");
if (!writeVectorToFile(tempZip, payload)) { result.message = "cannot write temp zip."; return result; }
if (!extractZipArchive(tempZip, zipPassword, outputPath)) {
fs::remove(tempZip);
result.message = "7zip extract failed. Wrong password or corrupted data.";
return result;
}
// 5) Remove used key
size_t remaining = removeKeyById(keysFilePath, keyIdHex);
fs::remove(tempZip);
result.success = true;
result.remainingKeys = remaining;
result.message = "Decryption OK. KID=" + keyIdHex + " -> " + outputPath;
return result;
}
} // namespace EncryptionLib