Repository navigation
Expand file tree
/
Copy pathaes.cpp
More file actions
285 lines (243 loc) · 9.15 KB
/
Copy pathaes.cpp
File metadata and controls
285 lines (243 loc) · 9.15 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
#include "aes.h"
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <limits>
#include <memory>
namespace {
const int kVersion = 1;
const int kMagicSize = 8;
const int kSaltSize = 16;
const int kIvSize = 12;
const int kTagSize = 16;
const int kKeySize = 32;
// magic + version + iterations + salt + iv,也是 GCM 的 AAD。
const int kAadSize = kMagicSize + 4 + 4 + kSaltSize + kIvSize;
const int kHeaderSize = kAadSize + kTagSize;
// 用于新备份的 PBKDF2 迭代次数;解密时以文件头记录的值为准。
const quint32 kDefaultIterations = 600000;
const quint32 kMinIterations = 10000;
const quint32 kMaxIterations = 5000000;
bool reportError(QString *errorMessage, const QString &message) {
if (errorMessage) {
*errorMessage = message;
}
return false;
}
void appendUint32(QByteArray &out, quint32 value) {
out.append(static_cast<char>((value >> 24) & 0xff));
out.append(static_cast<char>((value >> 16) & 0xff));
out.append(static_cast<char>((value >> 8) & 0xff));
out.append(static_cast<char>(value & 0xff));
}
quint32 readUint32(const QByteArray &data, int offset) {
const unsigned char *p =
reinterpret_cast<const unsigned char *>(data.constData()) + offset;
return (static_cast<quint32>(p[0]) << 24) |
(static_cast<quint32>(p[1]) << 16) |
(static_cast<quint32>(p[2]) << 8) |
static_cast<quint32>(p[3]);
}
QByteArray makeAad(const QByteArray &salt, const QByteArray &iv,
quint32 iterations) {
QByteArray aad;
aad.reserve(kAadSize);
aad.append(QByteArrayLiteral("ISHELLBK"));
appendUint32(aad, static_cast<quint32>(kVersion));
appendUint32(aad, iterations);
aad.append(salt);
aad.append(iv);
return aad;
}
bool deriveKey(const QString &password, const QByteArray &salt,
quint32 iterations, QByteArray *key, QString *errorMessage) {
key->resize(kKeySize);
QByteArray passwordBytes = password.toUtf8();
const int result = PKCS5_PBKDF2_HMAC(
passwordBytes.constData(), static_cast<int>(passwordBytes.size()),
reinterpret_cast<const unsigned char *>(salt.constData()),
static_cast<int>(salt.size()), static_cast<int>(iterations), EVP_sha256(),
kKeySize, reinterpret_cast<unsigned char *>(key->data()));
if (!passwordBytes.isEmpty()) {
OPENSSL_cleanse(passwordBytes.data(),
static_cast<size_t>(passwordBytes.size()));
}
if (result != 1) {
key->clear();
return reportError(errorMessage, QStringLiteral("无法派生加密密钥。"));
}
return true;
}
// encrypt 时 tag 为空、outTag 必填;decrypt 时 tag 为文件头中的认证标签。
bool gcmCrypt(const QByteArray &input, const QByteArray &aad,
const QByteArray &key, const QByteArray &iv,
const QByteArray &tag, bool encrypt, QByteArray *output,
QByteArray *outTag, QString *errorMessage) {
if (!output) {
return reportError(errorMessage, QStringLiteral("内部错误:输出参数为空。"));
}
if (key.size() != kKeySize || iv.size() != kIvSize ||
(encrypt && (!outTag || tag.size() != 0)) ||
(!encrypt && tag.size() != kTagSize)) {
return reportError(errorMessage,
QStringLiteral("内部错误:AES 参数无效。"));
}
if (input.size() > std::numeric_limits<int>::max() - EVP_MAX_BLOCK_LENGTH ||
aad.size() > std::numeric_limits<int>::max()) {
return reportError(errorMessage,
QStringLiteral("数据过大,无法使用 AES 处理。"));
}
output->clear();
if (outTag) {
outTag->clear();
}
const int inputSize = static_cast<int>(input.size());
QByteArray result(inputSize + EVP_MAX_BLOCK_LENGTH, '\0');
std::unique_ptr<EVP_CIPHER_CTX, void (*)(EVP_CIPHER_CTX *)> ctx(
EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
if (!ctx) {
return reportError(errorMessage,
QStringLiteral("无法初始化 OpenSSL 加密上下文。"));
}
const int mode = encrypt ? 1 : 0;
bool ok = EVP_CipherInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr, nullptr,
nullptr, mode) == 1;
if (ok) {
ok = EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, kIvSize,
nullptr) == 1;
}
if (ok) {
ok = EVP_CipherInit_ex(
ctx.get(), nullptr, nullptr,
reinterpret_cast<const unsigned char *>(key.constData()),
reinterpret_cast<const unsigned char *>(iv.constData()), mode) == 1;
}
// GCM 的 AAD 不产生输出,按 OpenSSL 约定把 out 传 nullptr。
int aadWritten = 0;
if (ok && !aad.isEmpty()) {
ok = EVP_CipherUpdate(
ctx.get(), nullptr, &aadWritten,
reinterpret_cast<const unsigned char *>(aad.constData()),
static_cast<int>(aad.size())) == 1;
}
int written = 0;
if (ok && inputSize > 0) {
ok = EVP_CipherUpdate(
ctx.get(), reinterpret_cast<unsigned char *>(result.data()),
&written, reinterpret_cast<const unsigned char *>(input.constData()),
inputSize) == 1;
}
if (ok && !encrypt) {
ok = EVP_CIPHER_CTX_ctrl(
ctx.get(), EVP_CTRL_GCM_SET_TAG, kTagSize,
const_cast<char *>(tag.constData())) == 1;
}
int finalWritten = 0;
if (ok) {
ok = EVP_CipherFinal_ex(
ctx.get(),
reinterpret_cast<unsigned char *>(result.data()) + written,
&finalWritten) == 1;
}
if (ok && encrypt) {
QByteArray generatedTag(kTagSize, '\0');
ok = EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kTagSize,
generatedTag.data()) == 1;
if (ok) {
*outTag = generatedTag;
}
}
if (!ok) {
OPENSSL_cleanse(result.data(), static_cast<size_t>(result.size()));
if (encrypt) {
return reportError(errorMessage,
QStringLiteral("OpenSSL AES-GCM 加密失败。"));
}
return reportError(errorMessage,
QStringLiteral("密码错误或备份文件已损坏。"));
}
result.resize(written + finalWritten);
*output = result;
return true;
}
} // namespace
bool AES::encrypt(const QByteArray &plaintext, const QString &password,
QByteArray *ciphertext, QString *errorMessage) {
if (!ciphertext) {
return reportError(errorMessage, QStringLiteral("内部错误:输出参数为空。"));
}
ciphertext->clear();
QByteArray salt(kSaltSize, '\0');
QByteArray iv(kIvSize, '\0');
if (RAND_bytes(reinterpret_cast<unsigned char *>(salt.data()),
static_cast<int>(salt.size())) != 1 ||
RAND_bytes(reinterpret_cast<unsigned char *>(iv.data()),
static_cast<int>(iv.size())) != 1) {
return reportError(errorMessage,
QStringLiteral("无法生成随机盐值或 IV。"));
}
QByteArray key;
if (!deriveKey(password, salt, kDefaultIterations, &key, errorMessage)) {
return false;
}
const QByteArray aad = makeAad(salt, iv, kDefaultIterations);
QByteArray body;
QByteArray tag;
const bool ok = gcmCrypt(plaintext, aad, key, iv, QByteArray(), true, &body,
&tag, errorMessage);
OPENSSL_cleanse(key.data(), static_cast<size_t>(key.size()));
if (!ok) {
return false;
}
QByteArray blob = aad;
blob.append(tag);
blob.append(body);
*ciphertext = blob;
return true;
}
bool AES::decrypt(const QByteArray &ciphertext, const QString &password,
QByteArray *plaintext, QString *errorMessage) {
if (!plaintext) {
return reportError(errorMessage, QStringLiteral("内部错误:输出参数为空。"));
}
plaintext->clear();
if (ciphertext.size() < kHeaderSize) {
return reportError(errorMessage,
QStringLiteral("备份文件格式无效或已损坏。"));
}
if (ciphertext.left(kMagicSize) != QByteArrayLiteral("ISHELLBK")) {
return reportError(errorMessage,
QStringLiteral("不是有效的 ishell 备份文件。"));
}
const quint32 version = readUint32(ciphertext, kMagicSize);
if (version != static_cast<quint32>(kVersion)) {
return reportError(errorMessage,
QStringLiteral("不支持的备份文件版本。"));
}
const quint32 iterations = readUint32(ciphertext, kMagicSize + 4);
if (iterations < kMinIterations || iterations > kMaxIterations) {
return reportError(errorMessage,
QStringLiteral("备份文件参数无效或已损坏。"));
}
const QByteArray salt =
ciphertext.mid(kMagicSize + 8, kSaltSize);
const QByteArray iv =
ciphertext.mid(kMagicSize + 8 + kSaltSize, kIvSize);
const QByteArray tag =
ciphertext.mid(kMagicSize + 8 + kSaltSize + kIvSize, kTagSize);
const QByteArray aad = ciphertext.left(kAadSize);
const QByteArray body = ciphertext.mid(kHeaderSize);
QByteArray key;
if (!deriveKey(password, salt, iterations, &key, errorMessage)) {
return false;
}
QByteArray plain;
const bool ok = gcmCrypt(body, aad, key, iv, tag, false, &plain, nullptr,
errorMessage);
OPENSSL_cleanse(key.data(), static_cast<size_t>(key.size()));
if (!ok) {
return false;
}
*plaintext = plain;
return true;
}