-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoHelper.cpp
More file actions
661 lines (490 loc) · 11.9 KB
/
Copy pathCryptoHelper.cpp
File metadata and controls
661 lines (490 loc) · 11.9 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
#include "CryptoHelper.h"
#include <crypto++/pwdbased.h>
#include <crypto++/secblock.h>
#include <crypto++/base64.h>
#include <crypto++/files.h>
#include <crypto++/pssr.h>
#include <crypto++/sha.h>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <libutils/Logger.h>
#include <libutils/String.h>
#include <libutils/Process.h>
using namespace std;
using namespace CryptoPP;
using namespace Utils;
namespace OPI {
namespace CryptoHelper {
/*
*
* Begin implementation RSA wrapper
*
*/
RSAWrapper::RSAWrapper(): priv_i(false), pub_i(false)
{
}
void RSAWrapper::GenerateKeys(unsigned int size)
{
InvertibleRSAFunction params;
params.GenerateRandomWithKeySize( this->rng, size);
this->privkey = PrivateKeyPtr( new RSA::PrivateKey( params) );
this->pubkey = PublicKeyPtr( new RSA::PublicKey(params) );
this->priv_i = true;
this->pub_i = true;
}
void RSAWrapper::LoadPrivKey(const string &path)
{
ByteQueue q;
FileSource file(path.c_str(), true);
file.TransferTo(q);
q.MessageEnd();
this->privkey = PrivateKeyPtr( new RSA::PrivateKey( ) );
this->privkey->Load(q);
this->ValidatePrivKey();
this->priv_i = true;
}
void RSAWrapper::LoadPubKey(const string &path)
{
ByteQueue q;
FileSource file(path.c_str(), true);
file.TransferTo(q);
q.MessageEnd();
this->pubkey = PublicKeyPtr( new RSA::PublicKey() );
this->pubkey->Load(q);
this->ValidatePubKey();
this->pub_i = true;
}
vector<byte> RSAWrapper::GetPubKey()
{
if( ! this->pub_i )
{
throw runtime_error("Public key not loaded");
}
ByteQueue q;
this->pubkey->Save(q);
vector<byte> ret(q.TotalBytesRetrievable() );
ArraySink sink(&ret[0],ret.size() );
q.CopyTo( sink );
return ret;
}
vector<byte> RSAWrapper::GetPubKeyAsDER()
{
ByteQueue q;
this->pubkey->DEREncode(q);
vector<byte> ret(q.TotalBytesRetrievable() );
ArraySink sink(&ret[0],ret.size() );
q.CopyTo( sink );
return ret;
}
vector<byte> RSAWrapper::GetPrivKey()
{
if( ! this->priv_i )
{
throw runtime_error("Private key not loaded");
}
ByteQueue q;
this->privkey->Save(q);
vector<byte> ret(q.TotalBytesRetrievable() );
ArraySink sink(&ret[0],ret.size() );
q.CopyTo( sink );
return ret;
}
vector<byte> RSAWrapper::GetPrivKeyAsDER()
{
ByteQueue q;
this->privkey->DEREncodePrivateKey(q);
vector<byte> ret(q.TotalBytesRetrievable() );
ArraySink sink(&ret[0],ret.size() );
q.CopyTo( sink );
return ret;
}
void RSAWrapper::SavePrivKey(const string &path, mode_t setmask)
{
if( ! this->priv_i )
{
throw runtime_error("Private key not loaded");
}
mode_t mask = umask(setmask);
ByteQueue queue;
this->privkey->Save(queue);
FileSink file(path.c_str());
queue.CopyTo(file);
file.MessageEnd();
umask( mask );
}
void RSAWrapper::SavePubKey(const string &path, mode_t setmask)
{
if( ! this->pub_i )
{
throw runtime_error("Public key not loaded");
}
mode_t mask = umask(setmask);
ByteQueue queue;
this->pubkey->Save(queue);
FileSink file(path.c_str());
queue.CopyTo(file);
file.MessageEnd();
umask( mask );
}
string RSAWrapper::PubKeyAsPEM()
{
if( ! this->pub_i )
{
throw runtime_error("Public key not loaded");
}
ByteQueue queue;
this->pubkey->DEREncode(queue);
string cert;
Base64Encoder encoder;
encoder.Attach( new StringSink(cert) );
queue.CopyTo( encoder );
encoder.MessageEnd();
stringstream ss;
ss << "-----BEGIN PUBLIC KEY-----\n";
ss << cert;
ss << "-----END PUBLIC KEY-----\n";
return ss.str();
}
string RSAWrapper::PrivKeyAsPEM()
{
if( ! this->priv_i )
{
throw runtime_error("Private key not loaded");
}
ByteQueue queue;
this->privkey->DEREncodePrivateKey(queue);
string cert;
Base64Encoder encoder;
encoder.Attach( new StringSink(cert) );
queue.CopyTo( encoder );
encoder.MessageEnd();
stringstream ss;
ss << "-----BEGIN RSA PRIVATE KEY-----\n";
ss << cert;
ss << "-----END RSA PRIVATE KEY-----\n";
return ss.str();
}
void RSAWrapper::LoadPrivKey(const vector<byte> &key)
{
ByteQueue q;
q.Put(&key[0], key.size() );
this->privkey = PrivateKeyPtr( new RSA::PrivateKey( ) );
this->privkey->Load(q);
this->ValidatePrivKey();
this->priv_i = true;
}
void RSAWrapper::LoadPrivKeyFromPEM(const string &key)
{
this->LoadPrivKeyFromDER( RSAWrapper::PEMToDER(key) );
}
/*
* We actually use BER decode but never mind.
*/
void RSAWrapper::LoadPrivKeyFromDER(const vector<byte> &key)
{
ByteQueue q;
q.Put(&key[0], key.size() );
this->privkey = PrivateKeyPtr( new RSA::PrivateKey() );
this->privkey->BERDecodePrivateKey( q, false, q.MaxRetrievable() );
this->ValidatePrivKey();
this->priv_i = true;
}
void RSAWrapper::LoadPubKey(const vector<byte> &key)
{
ByteQueue q;
q.Put(&key[0], key.size() );
this->pubkey = PublicKeyPtr( new RSA::PublicKey() );
this->pubkey->Load(q);
this->ValidatePubKey();
this->pub_i = true;
}
void RSAWrapper::LoadPubKeyFromPEM(const string &key)
{
this->LoadPubKeyFromDER( RSAWrapper::PEMToDER(key) );
}
void RSAWrapper::LoadPubKeyFromDER(const vector<byte> &key)
{
ByteQueue q;
q.Put(&key[0], key.size() );
this->pubkey = PublicKeyPtr( new RSA::PublicKey() );
this->pubkey->BERDecode( q );
this->ValidatePubKey();
this->pub_i = true;
}
vector<byte> RSAWrapper::SignMessage(const string &message)
{
if( ! this->priv_i )
{
throw runtime_error("Private key not loaded");
}
RSASS<PKCS1v15, SHA1>::Signer signer( *this->privkey.get() );
SecByteBlock signature( signer.MaxSignatureLength() );
// Sign message
signer.SignMessage( this->rng, (const byte*) message.c_str(),
message.length(), signature );
return vector<byte>(signature.begin(), signature.end());
}
bool RSAWrapper::VerifyMessage(const string &message, const string& signature)
{
if( ! this->pub_i )
{
throw runtime_error("Public key not loaded");
}
RSASS<PKCS1v15, SHA1>::Verifier verifier( *this->pubkey.get() );
bool result = verifier.VerifyMessage( (const byte*)message.c_str(),
message.length(), (const byte*)signature.c_str(), signature.length() );
return result;
}
/*
* TODO: Merge these two to something more intelligent?
*/
bool RSAWrapper::VerifyMessage(const string &message, const vector<byte> &signature)
{
if( ! this->pub_i )
{
throw runtime_error("Public key not loaded");
}
RSASS<PKCS1v15, SHA1>::Verifier verifier( *this->pubkey.get() );
bool result = verifier.VerifyMessage( (const byte*)message.c_str(),
message.length(), &signature[0], signature.size() );
return result;
}
vector<byte> RSAWrapper::PEMToDER(const string &key)
{
list<string> rows = String::Split(key, "\n");
if( rows.size() < 3 )
{
logg << Logger::Debug << "Key\n"<<key<<lend;
logg << Logger::Debug << "Rows "<<rows.size()<<lend;
throw runtime_error("Malformed PEM key");
}
// Lose first and last line
rows.pop_back();
rows.pop_front();
// Merge rows again
stringstream ss;
for(auto& row: rows)
{
ss << row;
}
return Base64Decode( ss.str() );
}
void RSAWrapper::ValidatePrivKey()
{
if(! this->privkey->Validate( this->rng, 3) )
{
throw runtime_error("Rsa private key validation failed");
}
}
void RSAWrapper::ValidatePubKey()
{
if(! this->pubkey->Validate( this->rng, 3) )
{
throw runtime_error("Rsa public key validation failed");
}
}
/*
*
* Begin implementation Stringtools
*
*/
string Base64Encode ( const vector<byte>& in )
{
string encoded;
ArraySource(&in[0], in.size(), true,
new Base64Encoder(
new StringSink( encoded ), false
)
);
return encoded;
}
string Base64Encode(const string& s)
{
string encoded;
StringSource ss( s, true,
new Base64Encoder(
new StringSink( encoded ), false
)
);
return encoded;
}
vector<byte> Base64Decode(const string &data)
{
//TODO: How avoid intermediate string?
string decoded;
StringSource ss( data, true,
new Base64Decoder(
new StringSink( decoded )
)
);
vector<byte> ret( decoded.size() );
std::copy(decoded.begin(), decoded.end(), ret.begin() );
return ret;
}
string Base64DecodeToString(const string& s)
{
string decoded;
StringSource ss( s, true,
new Base64Decoder(
new StringSink( decoded )
)
);
return decoded;
}
void
Base64Decode ( const string& s, vector<byte>& out )
{
string decoded = Base64DecodeToString(s);
out.resize( decoded.size() );
std::copy(decoded.begin(), decoded.end(), out.begin() );
}
void
Base64Decode ( const string& s, SecVector<byte>& out )
{
//TODO: the string here is not allocated with wiped allocator
string decoded = Base64DecodeToString(s);
out.resize( decoded.size() );
std::copy(decoded.begin(), decoded.end(), out.begin() );
}
/*
*
* Begin implementatsion AES wrapper
*
*/
vector<byte> AESWrapper::defaultiv = {
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
};
AESWrapper::AESWrapper(const SecVector<byte>& key, const vector<byte>& iv)
{
this->Initialize(key, iv);
}
AESWrapper::AESWrapper ()
{
}
void
AESWrapper::Initialize ( const SecVector<byte>& key, const vector<byte>& iv )
{
this->key = key;
this->iv = iv;
#if 0
this->e.SetKeyWithIV( &key[0], key.size(), &iv[0] );
this->d.SetKeyWithIV( &key[0], key.size(), &iv[0] );
#endif
}
string AESWrapper::Encrypt(const string& plain)
{
this->e.SetKeyWithIV( &this->key[0], this->key.size(), &this->iv[0] );
string ciphered;
StringSource s(plain, true,
new StreamTransformationFilter( this->e,
new StringSink(ciphered)
)
);
return ciphered;
}
void
AESWrapper::Encrypt ( const vector<byte>& in, vector<byte>& out )
{
this->e.SetKeyWithIV( &this->key[0], this->key.size(), &this->iv[0] );
string enc;
StringSource s( &in[0], in.size(), true,
new StreamTransformationFilter( this->e,
new StringSink(enc)
)
);
out.resize(enc.size());
copy(enc.begin(), enc.end(), out.begin() );
}
string AESWrapper::Decrypt(const string& encoded)
{
this->d.SetKeyWithIV( &this->key[0], this->key.size(), &this->iv[0] );
string plain;
logg << Logger::Debug << "Decode string size "<<encoded.size()<<lend;
StringSource s(encoded, true,
new StreamTransformationFilter(this->d,
new StringSink(plain)
)
);
return plain;
}
void
AESWrapper::Decrypt ( const vector<byte>& in, vector<byte>& out )
{
//Todo: investigate if the copy could be avoided.
string plain = this->Decrypt(in);
out.resize(plain.size());
copy(plain.begin(), plain.end(), out.begin() );
}
string
AESWrapper::Decrypt ( const vector<byte>& in )
{
this->d.SetKeyWithIV( &this->key[0], this->key.size(), &this->iv[0] );
string plain;
StringSource s( &in[0], in.size(), true,
new StreamTransformationFilter( this->d,
new StringSink(plain)
)
);
return plain;
}
const vector<byte> defaultsalt( {
33, 31, 2, 238, 199, 213, 62,
70, 132, 179, 13, 251, 120,
29, 251, 69, 216, 120, 141, 19,
177, 102, 3, 49, 165, 5, 120,
159, 191, 117, 240, 125, 235,
75, 158, 112, 67, 172, 57, 123,
175, 203, 37, 94, 57, 99, 237,
225, 238, 122, 213, 86, 182, 181,
251, 192, 142, 41, 105, 163, 1,
132, 52, 97
} );
SecVector<byte>
PBKDF2 (const SecString &passwd, size_t keylength, const vector<byte>& salt,
unsigned int iter )
{
SecVector<byte> ret(keylength);
PKCS5_PBKDF2_HMAC<SHA512> df;
df.DeriveKey(
&ret[0], ret.size(),
0,
(const byte*)passwd.c_str(), passwd.length(),
&salt[0],
salt.size(),
iter);
return ret;
}
void
AESWrapper::SetDefaultIV ( const vector<byte>& iv )
{
AESWrapper::defaultiv = iv;
}
AESWrapper::~AESWrapper()
{
}
bool MakeCSR(const string &privkeypath, const string &csrpath, const string &cn, const string &company)
{
stringstream cmd;
cmd << "/usr/bin/openssl ";
cmd << "req -out \""<< csrpath << "\" -key \""<< privkeypath << "\" -new -subj '/O="<<company<<"/CN="<<cn<<"'";
bool ret;
tie(ret, ignore) = Process::Exec(cmd.str() );
return ret;
}
bool MakeSelfSignedCert(const string &privkeypath, const string &certpath, const string &cn, const string &company)
{
stringstream cmd;
// TODO: Parametrizise digest and vailidity
cmd << "/usr/bin/openssl ";
cmd << "req -x509 -sha512 -key " << privkeypath << " -out " << certpath << " -days 365 -subj '/O=" << company <<"/CN=" << cn <<"'";
bool ret;
tie(ret, ignore) = Process::Exec(cmd.str() );
return ret;
}
}
}