-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.cc
402 lines (320 loc) · 10.9 KB
/
crypto.cc
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
//
// Durbatuluk is Copyright (c) 2012 Joel Odom
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "crypto.h"
#include "openssl_aes.h"
#include "logger.h"
#include "base64.h"
#include <openssl/engine.h>
/*static*/ bool Crypto::ExtractPublicRSAKey(const RSA* rsa, RSAKey* public_key)
{
unsigned char* buf = AllocateForRSAExtraction(rsa);
if (buf == nullptr)
return false; // failure
int len = BN_bn2bin(rsa->n, buf);
public_key->set_n(buf, len);
len = BN_bn2bin(rsa->e, buf);
public_key->set_e(buf, len);
delete[] buf;
return true; // success
}
/*static*/ bool Crypto::ExtractPrivateRSAKey(
const RSA* rsa, RSAKey* private_key)
{
unsigned char* buf = AllocateForRSAExtraction(rsa);
if (buf == nullptr)
return false; // failure
int len = BN_bn2bin(rsa->n, buf);
private_key->set_n(buf, len);
len = BN_bn2bin(rsa->e, buf);
private_key->set_e(buf, len);
len = BN_bn2bin(rsa->d, buf);
private_key->set_d(buf, len);
len = BN_bn2bin(rsa->p, buf);
private_key->set_p(buf, len);
len = BN_bn2bin(rsa->q, buf);
private_key->set_q(buf, len);
len = BN_bn2bin(rsa->dmp1, buf);
private_key->set_dmp1(buf, len);
len = BN_bn2bin(rsa->dmq1, buf);
private_key->set_dmq1(buf, len);
len = BN_bn2bin(rsa->iqmp, buf);
private_key->set_iqmp(buf, len);
delete[] buf;
return true; // success
}
/*static*/ bool Crypto::ImportRSAKey(const RSAKey& rsa_key, RSA* rsa)
{
ExtractBIGNUM(rsa_key.n(), &rsa->n);
if (rsa->n == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.e(), &rsa->e);
if (rsa->e == nullptr)
return false; // failure
if (rsa_key.has_d() && rsa_key.has_p() && rsa_key.has_q()
&& rsa_key.has_dmp1() && rsa_key.has_dmq1() && rsa_key.has_iqmp())
{
// private keys are currently all or nothing
ExtractBIGNUM(rsa_key.d(), &rsa->d);
if (rsa->d == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.p(), &rsa->p);
if (rsa->p == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.q(), &rsa->q);
if (rsa->q == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.dmp1(), &rsa->dmp1);
if (rsa->dmp1 == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.dmq1(), &rsa->dmq1);
if (rsa->dmq1 == nullptr)
return false; // failure
ExtractBIGNUM(rsa_key.iqmp(), &rsa->iqmp);
if (rsa->iqmp == nullptr)
return false; // failure
if (RSA_check_key(rsa) != 1)
{
Logger::LogMessage(ERROR, "Crypto", "RSA_check_key indicated problem");
return false; // failure
}
}
return true; // success
}
/*static*/ unsigned char* Crypto::AllocateForRSAExtraction(const RSA* rsa)
{
if (rsa->n == nullptr || rsa->e == nullptr)
return nullptr;
int bytes_needed = BN_num_bytes(rsa->n);
int i = BN_num_bytes(rsa->e);
if (i > bytes_needed)
bytes_needed = i;
if (rsa->d != nullptr)
{
i = BN_num_bytes(rsa->d);
if (i > bytes_needed)
bytes_needed = i;
}
if (rsa->p != nullptr)
{
i = BN_num_bytes(rsa->p);
if (i > bytes_needed)
bytes_needed = i;
}
if (rsa->q != nullptr)
{
i = BN_num_bytes(rsa->q);
if (i > bytes_needed)
bytes_needed = i;
}
if (rsa->dmp1 != nullptr)
{
i = BN_num_bytes(rsa->dmp1);
if (i > bytes_needed)
bytes_needed = i;
}
if (rsa->dmq1 != nullptr)
{
i = BN_num_bytes(rsa->dmq1);
if (i > bytes_needed)
bytes_needed = i;
}
if (rsa->iqmp != nullptr)
{
i = BN_num_bytes(rsa->iqmp);
if (i > bytes_needed)
bytes_needed = i;
}
return new unsigned char[bytes_needed];
}
/*static*/ void Crypto::ExtractBIGNUM(std::string s, BIGNUM** bn)
{
*bn = BN_bin2bn((const unsigned char*)s.c_str(), s.length(), nullptr);
}
/*static*/ bool Crypto::CreateSignedMessage(
const std::string& contents, RSA* rsa, SignedMessage* signed_message)
{
// set up variables and buffers
int rsa_size = RSA_size(rsa);
unsigned char sigret[rsa_size];
unsigned int siglen;
RSAKey public_key;
if (!ExtractPublicRSAKey(rsa, &public_key))
return false; // failure
// sign the contents
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)contents.c_str(), contents.length(), digest);
if (RSA_sign(NID_sha1, digest, SHA_DIGEST_LENGTH, sigret, &siglen, rsa) != 1)
return false; // failure
// build the SignedMessage
signed_message->mutable_sender()->set_n(public_key.n());
signed_message->mutable_sender()->set_e(public_key.e());
signed_message->set_contents(contents.c_str(), contents.length());
signed_message->set_signature(sigret, siglen);
return true; // failure
}
/*static*/ bool Crypto::VerifySignedMessage(const SignedMessage& signed_message)
{
// import the public signing key
RSA* rsa = RSA_new();
if (rsa == nullptr)
return false; // failure
if (!ImportRSAKey(signed_message.sender(), rsa))
{
RSA_free(rsa);
return false; // failure
}
// verify the digital signature
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)signed_message.contents().c_str(),
signed_message.contents().length(), digest);
bool signature_passed = RSA_verify(NID_sha1, digest, SHA_DIGEST_LENGTH,
(unsigned char*)signed_message.signature().c_str(),
signed_message.signature().length(), rsa);
RSA_free(rsa);
return signature_passed;
}
/*static*/ bool Crypto::EncryptMessage(const RSAKey& recipient_public_key,
const std::string& contents, EncryptedMessage* encrypted_message)
{
// import the public key
RSA* rsa = RSA_new();
if (rsa == nullptr)
return false; // failure
if (!ImportRSAKey(recipient_public_key, rsa))
return false; // failure
int rsa_size = RSA_size(rsa);
// set up for encryption early so that the session key stays in memory
// for as short a time as possible
unsigned char session_key[SESSION_KEY_LEN];
unsigned char* ciphertext = nullptr;
int len = (int)contents.length();
unsigned char encrypted_session_key[rsa_size];
EVP_CIPHER_CTX en, de;
// encrypt
while (true) // break out when finished
{
// generate a random session key
if (RAND_bytes(session_key, SESSION_KEY_LEN) != 1)
break; // couldn't generate cryptographically secure session key
// encrypt the session key
int i = RSA_public_encrypt(SESSION_KEY_LEN, session_key,
encrypted_session_key, rsa, RSA_PKCS1_OAEP_PADDING);
if (i != rsa_size)
break; // something went wrong
// encrypt the message contents with the session key
i = aes_init(session_key, SESSION_KEY_LEN, nullptr, &en, &de);
if (i != 0)
break; // couldn't initialize AES cipher
ciphertext = aes_encrypt(&en, (unsigned char*)contents.c_str(), &len);
break;
}
// dispose of session key as quickly as possible
memset((unsigned char*)session_key, 0, SESSION_KEY_LEN);
EVP_CIPHER_CTX_cleanup(&en);
EVP_CIPHER_CTX_cleanup(&de);
RSA_free(rsa); // remember this is only the receiver public key
bool success = false;
if (ciphertext != nullptr)
{
// populate the encrypted message
encrypted_message->mutable_recipient()->set_n(recipient_public_key.n());
encrypted_message->mutable_recipient()->set_e(recipient_public_key.e());
encrypted_message->set_encrypted_key(encrypted_session_key, rsa_size);
encrypted_message->set_encrypted_contents(ciphertext, len);
free(ciphertext); // (safe to free nullptr)
success = true;
}
return success;
}
/*static*/ bool Crypto::DecryptMessage(RSA* rsa,
const EncryptedMessage& encrypted_message, std::string* decrypted)
{
// verify that RSA key parameter is that of recipient of message
RSAKey private_key;
if (!ExtractPrivateRSAKey(rsa, &private_key))
{
Logger::LogMessage(ERROR, "Crypto", "ExtractPrivateRSAKey failed");
return false; // failure
}
if (encrypted_message.recipient().e() != private_key.e() // e usually smaller
|| encrypted_message.recipient().n() != private_key.n())
{
Logger::LogMessage(INFO, "Crypto", "Message is not for this recipient");
return false; // failure
}
// decrypt the message contents
decrypted->erase(); // for good measure
int rsa_size = RSA_size(rsa);
unsigned char session_key[rsa_size];
EVP_CIPHER_CTX en, de;
while (true) // break out when finished
{
// decrypt the session key
if (RSA_private_decrypt(rsa_size,
reinterpret_cast<const unsigned char*>(
encrypted_message.encrypted_key().c_str()),
session_key, rsa, RSA_PKCS1_OAEP_PADDING) < 0)
break; // failure
// decrypt the contents
int i = aes_init(session_key, SESSION_KEY_LEN, nullptr, &en, &de);
if (i != 0)
break; // couldn't initialize AES cipher
int len = encrypted_message.encrypted_contents().length();
char* plaintext = (char*)aes_decrypt(&de,
(unsigned char*)encrypted_message.encrypted_contents().c_str(), &len);
if (plaintext == nullptr)
break; // something went wrong with encryption
// place the contents in the decrypted string
if ((size_t)len > decrypted->max_size())
break; // message too long
decrypted->reserve(len);
for (i = 0; i < len; i++)
decrypted->push_back(plaintext[i]);
free(plaintext);
break;
}
// clean the session key from memory
memset(session_key, 0, SESSION_KEY_LEN);
EVP_CIPHER_CTX_cleanup(&en);
EVP_CIPHER_CTX_cleanup(&de);
if (decrypted->length() <= 0)
{
Logger::LogMessage(INFO, "Crypto", "Decryption failure");
return false; // failure
}
return true; // success
}
/*static*/ bool Crypto::HashRSAKey(const RSAKey& key, std::string* encoded_hash)
{
// serialize the key
std::string serialized;
if (!key.SerializeToString(&serialized))
{
Logger::LogMessage(ERROR, "Crypto", "SerializeToString failed");
return false; // failure
}
// hash the key
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1((const unsigned char*)serialized.c_str(), serialized.length(), digest);
// encode the hash
*encoded_hash = base64_encode(digest, SHA_DIGEST_LENGTH);
return true; // success
}