forked from paixaop/node-sodium
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeyring.cc
More file actions
1351 lines (1190 loc) · 47.6 KB
/
keyring.cc
File metadata and controls
1351 lines (1190 loc) · 47.6 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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#define BUILDING_NODE_EXTENSION
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <utility>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <node.h>
#include <node_buffer.h>
#include "keyring.h"
//Including libsodium export headers
#include "sodium.h"
using namespace v8;
using namespace node;
using namespace std;
#define PREPARE_FUNC_VARS() \
Nan::EscapableHandleScope scope; \
KeyRing* instance = ObjectWrap::Unwrap<KeyRing>(info.This());
//Defining "invlid number of parameters" macro
#define MANDATORY_ARGS(n, message) \
if (info.Length() < n){ \
Nan::ThrowError(message); \
info.GetReturnValue().Set(Nan::Undefined()); \
return; \
}
#define CHECK_KEYPAIR(type) \
if (instance->_keyType == ""){ \
Nan::ThrowTypeError("No key pair has been loaded into the key ring"); \
info.GetReturnValue().Set(Nan::Undefined()); \
return; \
} \
if (instance->_keyType != type){ \
Nan::ThrowTypeError("Invalid key type"); \
info.GetReturnValue().Set(Nan::Undefined()); \
return; \
}
#define BUILD_BUFFER_STRING(name, str) \
unsigned int name ## _size = str.length(); \
unsigned char* name ## _ptr = new unsigned char[str.length()]; \
memcpy(name ## _ptr, str.c_str(), str.length()); \
Local<Object> name = Nan::NewBuffer((char*) name ## _ptr, name ## _size).ToLocalChecked();
//unsigned char* name ## _ptr = (unsigned char*)Buffer::Data(name);
#define BUILD_BUFFER_CHAR(name, data, size) \
unsigned int name ## _size = size; \
Local<Object> name = Nan::NewBuffer(data, name ## _size).ToLocalChecked(); \
unsigned char* name ## _ptr = (unsigned char*)Buffer::Data(name);
#define BIND_METHOD(name, function) \
Nan::SetPrototypeMethod(tpl, name, function);
//tpl->PrototypeTemplate()->Set(String::NewSymbol(name), FunctionTemplate::New(function)->GetFunction());
//Persistent<Function> KeyRing::constructor;
KeyRing::KeyRing(string const& filename, unsigned char* password, size_t passwordSize) : _filename(filename), _privateKey(0), _publicKey(0), _altPrivateKey(0), _altPublicKey(0){
_keyLock = false;
if (filename != ""){
if (!doesFileExist(filename)){
//Throw a V8 exception??
return;
}
loadKeyPair(filename, &_keyType, _privateKey, _publicKey, password, passwordSize);
_filename = filename;
}
globalObj = Nan::GetCurrentContext()->Global();
bufferConstructor = Local<Function>::Cast(globalObj->Get(Nan::New<String>("Buffer").ToLocalChecked()));
}
KeyRing::~KeyRing(){
if (_privateKey != 0){
if (_keyType == "ed25519") sodium_memzero(_privateKey, crypto_sign_SECRETKEYBYTES);
else sodium_memzero(_privateKey, crypto_box_SECRETKEYBYTES);
delete _privateKey;
_privateKey = 0;
}
if (_publicKey != 0){
if (_keyType == "ed25519") sodium_memzero(_publicKey, crypto_sign_PUBLICKEYBYTES);
else sodium_memzero(_publicKey, crypto_box_PUBLICKEYBYTES);
delete _publicKey;
_publicKey = 0;
}
//Note : altKeys are always curve25519
if (_altPrivateKey != 0){
sodium_memzero(_altPrivateKey, crypto_box_SECRETKEYBYTES);
delete _altPrivateKey;
_altPrivateKey = 0;
}
if (_altPublicKey != 0){
sodium_memzero(_altPublicKey, crypto_box_PUBLICKEYBYTES);
delete _altPublicKey;
_altPublicKey = 0;
}
}
NAN_MODULE_INIT(KeyRing::Init){
//Prepare constructor template
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(KeyRing::New);
tpl->SetClassName(Nan::New("KeyRing").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(4);
//Prototype
BIND_METHOD("encrypt", Encrypt);
BIND_METHOD("decrypt", Decrypt);
BIND_METHOD("sign", Sign);
BIND_METHOD("agree", Agree);
BIND_METHOD("publicKeyInfo", PublicKeyInfo);
BIND_METHOD("createKeyPair", CreateKeyPair);
BIND_METHOD("load", Load);
BIND_METHOD("save", Save);
BIND_METHOD("clear", Clear);
BIND_METHOD("setKeyBuffer", SetKeyBuffer);
BIND_METHOD("getKeyBuffer", GetKeyBuffer);
BIND_METHOD("lockKeyBuffer", LockKeyBuffer);
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target, Nan::New("KeyRing").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
//cout << "KeyRing::Init" << endl;
}
/*
* JS -> C++ data constructor bridge
* Parameter : String filename [optional]
*/
NAN_METHOD(KeyRing::New){
//cout << "KeyRing::New ";
if (info.IsConstructCall()){
//cout << "ConstructCall" << endl;
//Invoked as a constructor
string filename;
unsigned char* password = 0;
size_t passwordSize = 0;
if (info[0]->IsUndefined()){
filename = "";
} else {
String::Utf8Value filenameVal(info[0]->ToString());
filename = string(*filenameVal);
}
if (info.Length() > 1 && !info[1]->IsUndefined()){
//Casting password
Local<Object> passwordVal = info[1]->ToObject();
password = (unsigned char*) Buffer::Data(passwordVal);
passwordSize = Buffer::Length(passwordVal);
}
KeyRing* newInstance = new KeyRing(filename, password, passwordSize);
newInstance->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
//Invoked as a plain function; turn it into construct call
//cout << "Plain call" << endl;
if (info.Length() > 2){
Nan::ThrowTypeError("Invalid number of arguments on KeyRing constructor call");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
Local<Function> cons = Nan::New(constructor());
if (info.Length() > 0){
unsigned int infoLength = info.Length();
Local<Value> * argvPtr = NULL;
if (infoLength == 1){
Local<Value> argv[1] = {info[0]};
argvPtr = argv;
} else if (infoLength == 2){
Local<Value> argv[2] = {info[0], info[1]};
argvPtr = argv;
}
info.GetReturnValue().Set(Nan::NewInstance(cons, infoLength, argvPtr).ToLocalChecked());
} else {
Local<Value> argv[0] = {};
info.GetReturnValue().Set(Nan::NewInstance(cons, 0, argv).ToLocalChecked());
}
/*if (info.Length() == 1){
Local<Value> argv[1] = { info[0] };
return scope.Close(constructor->NewInstance(1, argv));
} else {
return scope.Close(constructor->NewInstance());
}*/
}
}
/**
* Make a Curve25519 key exchange for a given public key, then encrypt the message (crypto_box)
* Parameters Buffer message, Buffer publicKey, Buffer nonce, callback (optional)
* Returns Buffer
*/
NAN_METHOD(KeyRing::Encrypt){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(3, "Mandatory args : message, counterpartPubKey, nonce\nOptional args: callback");
//CHECK_KEYPAIR("curve25519");
Local<Object> messageVal = info[0]->ToObject();
Local<Object> publicKeyVal = info[1]->ToObject();
Local<Object> nonceVal = info[2]->ToObject();
const unsigned char* message = (unsigned char*) Buffer::Data(messageVal);
const size_t messageLength = Buffer::Length(messageVal);
const unsigned char* publicKey = (unsigned char*) Buffer::Data(publicKeyVal);
const size_t publicKeyLength = Buffer::Length(publicKeyVal);
if (publicKeyLength != crypto_box_PUBLICKEYBYTES){
stringstream errMsg;
errMsg << "Public key must be " << crypto_box_PUBLICKEYBYTES << " bytes long";
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
const unsigned char* nonce = (unsigned char*) Buffer::Data(nonceVal);
const size_t nonceLength = Buffer::Length(nonceVal);
if (nonceLength != crypto_box_NONCEBYTES){
stringstream errMsg;
errMsg << "The nonce must be " << crypto_box_NONCEBYTES << " bytes long";
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
unsigned char* paddedMessage = new unsigned char[messageLength + crypto_box_ZEROBYTES];
for (unsigned int i = 0; i < crypto_box_ZEROBYTES; i++){
paddedMessage[i] = 0;
}
memcpy((void*) (paddedMessage + crypto_box_ZEROBYTES), (void*) message, messageLength);
Local<Object> cipherBuf = Nan::NewBuffer(messageLength + crypto_box_ZEROBYTES).ToLocalChecked();
unsigned char* cipher = (unsigned char*)Buffer::Data(cipherBuf);
int boxResult;
if (instance->_keyType == "curve25519"){
boxResult = crypto_box(cipher, paddedMessage, messageLength + crypto_box_ZEROBYTES, nonce, publicKey, instance->_privateKey);
} else {
boxResult = crypto_box(cipher, paddedMessage, messageLength + crypto_box_ZEROBYTES, nonce, publicKey, instance->_altPrivateKey);
}
if (boxResult != 0){
stringstream errMsg;
errMsg << "Error while encrypting message. Error code : " << boxResult;
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//BUILD_BUFFER(string((char*) cipher, message.length()).c_str());
if (!(info.Length() > 3 && info[3]->IsFunction())){
info.GetReturnValue().Set(cipherBuf);
} else {
//BUILD_BUFFER_CHAR(result, (char*)cipher, messageLength + crypto_box_ZEROBYTES);
Local<Function> callback = Local<Function>::Cast(info[3]);
const int argc = 1;
Local<Value> argv[argc] = { cipherBuf };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
/*
* Decrypt a message, using crypto_box_open
* Args : Buffer cipher, Buffer publicKey, Buffer nonce, Function callback (optional)
*/
NAN_METHOD(KeyRing::Decrypt){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(3, "Mandatory args : cipher, counterpartPubKey, nonce\nOptional args: callback");
//CHECK_KEYPAIR("curve25519");
Local<Object> cipherVal = info[0]->ToObject();
Local<Object> publicKeyVal = info[1]->ToObject();
Local<Object> nonceVal = info[2]->ToObject();
const unsigned char* cipher = (unsigned char*) Buffer::Data(cipherVal);
const size_t cipherLength = Buffer::Length(cipherVal);
//Checking that the first crypto_box_BOXZEROBYTES are zeros
unsigned int i = 0;
for (i = 0; i < crypto_box_BOXZEROBYTES; i++){
if (cipher[i]) break;
}
if (i < crypto_box_BOXZEROBYTES){
stringstream errMsg;
errMsg << "The first " << crypto_box_BOXZEROBYTES << " bytes of the cipher argument must be zeros";
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
const unsigned char* publicKey = (unsigned char*) Buffer::Data(publicKeyVal);
const unsigned char* nonce = (unsigned char*) Buffer::Data(nonceVal);
unsigned char* message = new unsigned char[cipherLength];
int boxResult;
if (instance->_keyType == "curve25519"){
boxResult = crypto_box_open(message, cipher, cipherLength, nonce, publicKey, instance->_privateKey);
} else {
boxResult = crypto_box_open(message, cipher, cipherLength, nonce, publicKey, instance->_altPrivateKey);
}
if (boxResult != 0){
stringstream errMsg;
errMsg << "Error while decrypting message. Error code : " << boxResult;
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
unsigned char* plaintext = new unsigned char[cipherLength - crypto_box_ZEROBYTES];
memcpy(plaintext, (void*) (message + crypto_box_ZEROBYTES), cipherLength - crypto_box_ZEROBYTES);
//BUILD_BUFFER_CHAR(result, (char*)plaintext, cipherLength - crypto_box_ZEROBYTES);
if (!(info.Length() > 3 && info[3]->IsFunction())){
info.GetReturnValue().Set(Nan::NewBuffer((char*) plaintext, cipherLength - crypto_box_ZEROBYTES).ToLocalChecked());
return;
} else {
Local<Function> callback = Local<Function>::Cast(info[3]);
const int argc = 1;
Local<Value> argv[argc] = { Nan::NewBuffer((char*) plaintext, cipherLength - crypto_box_ZEROBYTES).ToLocalChecked() };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
/*
* Sign a given message, using crypto_sign
* Args: Buffer message, Function callback (optional), Boolean detachedSignature
*/
NAN_METHOD(KeyRing::Sign){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(1, "Mandatory args : message\nOptional args: callback, detachedSignature");
CHECK_KEYPAIR("ed25519");
Local<Value> messageVal = info[0]->ToObject();
const unsigned char* message = (unsigned char*) Buffer::Data(messageVal);
const size_t messageLength = Buffer::Length(messageVal);
bool detachedSignature = false;
if (info.Length() > 2){
Local<Boolean> detachedSignatureVal = info[2]->ToBoolean();
detachedSignature = detachedSignatureVal->Value();
}
unsigned long long signatureSize = (detachedSignature ? crypto_sign_BYTES : messageLength + crypto_sign_BYTES);
Local<Object> signatureBuf = Nan::NewBuffer(signatureSize).ToLocalChecked();
unsigned char* signature = (unsigned char*) Buffer::Data(signatureBuf);
int signResult;
if (detachedSignature){
signResult = crypto_sign_detached(signature, &signatureSize, message, messageLength, instance->_privateKey);
} else {
signResult = crypto_sign(signature, &signatureSize, message, messageLength, instance->_privateKey);
}
if (signResult != 0){
stringstream errMsg;
errMsg << "Error while signing the message. Code : " << signResult << endl;
Nan::ThrowTypeError(errMsg.str().c_str());
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//BUILD_BUFFER(string((char*) signature, messageLength + crypto_sign_BYTES).c_str());
if (!(info.Length() > 1 && info[1]->IsFunction())){
info.GetReturnValue().Set(signatureBuf);
return;
} else {
//BUILD_BUFFER_CHAR(result, (char*) signature, signatureSize);
Local<Function> callback = Local<Function>::Cast(info[1]);
const int argc = 1;
Local<Value> argv[argc] = { signatureBuf };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
/*
* Do a Curve25519 key-exchange
* Args : Buffer counterpartPubKey, Function callback (optional)
*/
NAN_METHOD(KeyRing::Agree){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(1, "Mandatory args : counterpartPubKey\nOptional: callback");
//CHECK_KEYPAIR("curve25519");
Local<Object> publicKeyVal = info[0]->ToObject();
const unsigned char* counterpartPubKey = (unsigned char*) Buffer::Data(publicKeyVal);
Local<Object> sharedSecretBuf = Nan::NewBuffer(crypto_scalarmult_BYTES).ToLocalChecked();
unsigned char* sharedSecret = (unsigned char*) Buffer::Data(sharedSecretBuf);
if (instance->_keyType == "curve25519"){
crypto_scalarmult(sharedSecret, instance->_privateKey, counterpartPubKey);
} else {
crypto_scalarmult(sharedSecret, instance->_altPrivateKey, counterpartPubKey);
}
if (!(info.Length() > 1 && info[1]->IsFunction())){
info.GetReturnValue().Set(sharedSecretBuf);
return;
} else {
//BUILD_BUFFER_CHAR(result, (char*) sharedSecret, crypto_scalarmult_BYTES);
Local<Function> callback = Local<Function>::Cast(info[1]);
const int argc = 1;
Local<Value> argv[argc] = { sharedSecretBuf };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
//Function callback (optional)
NAN_METHOD(KeyRing::PublicKeyInfo){
PREPARE_FUNC_VARS();
//Checking that a keypair is loaded in memory
if (instance->_keyType == "" || instance->_privateKey == 0 || instance->_publicKey == 0){
Nan::ThrowTypeError("No key has been loaded into memory");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//Sync/async fork
if (!(info.Length() > 0 && info[0]->IsFunction())){
info.GetReturnValue().Set(instance->PPublicKeyInfo());
return;
} else {
Local<Function> callback = Local<Function>::Cast(info[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = { instance->PPublicKeyInfo() };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
Local<Object> KeyRing::PPublicKeyInfo(){
Local<Object> pubKeyObj = Nan::New<v8::Object>();
if (_keyType == "" || _privateKey == 0 || _publicKey == 0){
throw new runtime_error("No loaded key pair");
}
//string keyType = keyPair->at("keyType");
string publicKey = strToHex(string((char*) _publicKey, ((_keyType == "ed25519") ? crypto_sign_PUBLICKEYBYTES : crypto_box_PUBLICKEYBYTES)));
pubKeyObj->ForceSet(Nan::New<String>("keyType").ToLocalChecked(), Nan::New<String>(_keyType.c_str()).ToLocalChecked());
pubKeyObj->ForceSet(Nan::New<String>("publicKey").ToLocalChecked(), Nan::New<String>(publicKey.c_str()).ToLocalChecked());
if (_keyType == "ed25519"){
string altPubKey = strToHex(string((char*) _altPublicKey, crypto_box_PUBLICKEYBYTES));
pubKeyObj->ForceSet(Nan::New<String>("curvePublicKey").ToLocalChecked(), Nan::New<String>(altPubKey.c_str()).ToLocalChecked());
} else {
pubKeyObj->ForceSet(Nan::New<String>("curvePublicKey").ToLocalChecked(), Nan::New<String>(publicKey.c_str()).ToLocalChecked());
}
return pubKeyObj;
}
/*
* Generates a keypair. Save it to filename if given
* String keyType, String filename [optional], Function callback [optional], Buffer passoword [optional], Number opsLimit [optional], Number r [optional], Number p [optional]
*/
NAN_METHOD(KeyRing::CreateKeyPair){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(1, "Please give the type of the key you want to generate");
String::Utf8Value keyTypeVal(info[0]->ToString());
string keyType(*keyTypeVal);
if (!(keyType == "ed25519" || keyType == "curve25519")) {
Nan::ThrowTypeError("Invalid key type");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//Delete the keypair loaded in memory, part by part, if any
if (instance->_privateKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_privateKey, crypto_sign_SECRETKEYBYTES);
else sodium_memzero(instance->_privateKey, crypto_box_SECRETKEYBYTES);
delete instance->_privateKey;
instance->_privateKey = 0;
}
if (instance->_publicKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_publicKey, crypto_sign_PUBLICKEYBYTES);
else sodium_memzero(instance->_publicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_publicKey;
instance->_publicKey = 0;
}
//Note : altKeys are always curve25519
if (instance->_altPrivateKey != 0){
sodium_memzero(instance->_altPrivateKey, crypto_box_SECRETKEYBYTES);
delete instance->_altPrivateKey;
instance->_altPrivateKey = 0;
}
if (instance->_altPublicKey != 0){
sodium_memzero(instance->_altPublicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_altPublicKey;
instance->_altPublicKey = 0;
}
if (instance->_keyType != ""){
instance->_keyType = "";
}
instance->_filename = "";
//Generating keypairs
if (keyType == "ed25519"){
unsigned char* privateKey = new unsigned char[crypto_sign_SECRETKEYBYTES];
unsigned char* publicKey = new unsigned char[crypto_sign_PUBLICKEYBYTES];
crypto_sign_keypair(publicKey, privateKey);
instance->_privateKey = privateKey;
instance->_publicKey = publicKey;
instance->_keyType = "ed25519";
instance->_altPublicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
instance->_altPrivateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
deriveAltKeys(instance->_publicKey, instance->_privateKey, instance->_altPublicKey, instance->_altPrivateKey);
} else if (keyType == "curve25519"){
unsigned char* privateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
unsigned char* publicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
crypto_box_keypair(publicKey, privateKey);
instance->_privateKey = privateKey;
instance->_publicKey = publicKey;
instance->_keyType = "curve25519";
}
if (info.Length() >= 2 && !info[1]->IsUndefined()){ //Save keypair to file
String::Utf8Value filenameVal(info[1]->ToString());
string filename(*filenameVal);
if (info.Length() > 3 && !info[3]->IsUndefined()){
Local<Value> passwordVal = info[3]->ToObject();
const unsigned char* password = (unsigned char*) Buffer::Data(passwordVal);
const size_t passwordSize = Buffer::Length(passwordVal);
if (info.Length() > 4){
unsigned long opsLimit = 16384;
unsigned short r = 8;
unsigned short p = 1;
if (info[4]->IsNumber()){
opsLimit = (unsigned long) info[4]->IntegerValue();
}
if (info.Length() > 5 && info[5]->IsNumber()){
r = (unsigned short) info[4]->Int32Value();
}
if (info.Length() > 6 && info[6]->IsNumber()){
p = (unsigned short) info[5]->Int32Value();
}
saveKeyPair(filename, keyType, instance->_privateKey, instance->_publicKey, password, passwordSize, opsLimit, r, p);
} else saveKeyPair(filename, keyType, instance->_privateKey, instance->_publicKey, password, passwordSize);
} else saveKeyPair(filename, keyType, instance->_privateKey, instance->_publicKey);
instance->_filename = filename;
}
if (info.Length() >= 3 && info[3]->IsFunction()){ //Callback
Local<Function> callback = Local<Function>::Cast(info[2]);
const unsigned argc = 1;
Local<Value> argv[argc] = { instance->PPublicKeyInfo() };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
} else {
info.GetReturnValue().Set(instance->PPublicKeyInfo());
return;
}
}
// String filename, Function callback (optional), password, maxOpsLimit
NAN_METHOD(KeyRing::Load){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(1, "Mandatory args : String filename\nOptional args : Function callback");
String::Utf8Value filenameVal(info[0]->ToString());
string filename(*filenameVal);
if (instance->_privateKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_privateKey, crypto_sign_SECRETKEYBYTES);
else sodium_memzero(instance->_privateKey, crypto_box_SECRETKEYBYTES);
delete instance->_privateKey;
instance->_privateKey = 0;
}
if (instance->_publicKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_publicKey, crypto_sign_PUBLICKEYBYTES);
else sodium_memzero(instance->_publicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_publicKey;
instance->_publicKey = 0;
}
//Note : altKeys are always curve25519
if (instance->_altPrivateKey != 0){
sodium_memzero(instance->_altPrivateKey, crypto_box_SECRETKEYBYTES);
delete instance->_altPrivateKey;
instance->_altPrivateKey = 0;
}
if (instance->_altPublicKey != 0){
sodium_memzero(instance->_altPublicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_altPublicKey;
instance->_altPublicKey = 0;
}
instance->_filename = "";
fstream fileReader(filename.c_str(), ios::in);
string keyStr;
getline(fileReader, keyStr);
fileReader.close();
if (keyStr[0] == 0x05){ //Curve25519
instance->_privateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
instance->_publicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
} else if (keyStr[0] == 0x06){
instance->_privateKey = new unsigned char[crypto_sign_SECRETKEYBYTES];
instance->_publicKey = new unsigned char[crypto_sign_PUBLICKEYBYTES];
} else {
Nan::ThrowTypeError("Invalid key file");
}
if (info.Length() > 2){
Local<Value> passwordVal = info[2]->ToObject();
const unsigned char* password = (unsigned char*) Buffer::Data(passwordVal);
const size_t passwordSize = Buffer::Length(passwordVal);
unsigned long maxOpsLimit = 4194304;
if (info.Length() > 3 && info[3]->IsNumber()){
maxOpsLimit = (unsigned long) info[3]->IntegerValue();
//cout << "MaxOpsLimit: " << maxOpsLimit << endl;
}
try {
loadKeyPair(filename, &(instance->_keyType), instance->_privateKey, instance->_publicKey, password, passwordSize, maxOpsLimit);
} catch (runtime_error* e){
Nan::ThrowTypeError(e->what());
info.GetReturnValue().Set(Nan::Undefined());
return;
} catch (void* e){
Nan::ThrowTypeError("Error while loading the encrypted key file");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
} else {
try {
loadKeyPair(filename, &(instance->_keyType), instance->_privateKey, instance->_publicKey);
} catch (runtime_error* e){
Nan::ThrowTypeError(e->what());
info.GetReturnValue().Set(Nan::Undefined());
return;
} catch (void* e){
Nan::ThrowTypeError("Error while loading the key file");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
if (instance->_keyType == "ed25519"){
instance->_altPublicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
instance->_altPrivateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
deriveAltKeys(instance->_publicKey, instance->_privateKey, instance->_altPublicKey, instance->_altPrivateKey);
}
instance->_filename = filename;
instance->PPublicKeyInfo();
if (info.Length() == 1){
info.GetReturnValue().Set( instance->PPublicKeyInfo() );
return;
} else {
if (!info[1]->IsFunction()){
info.GetReturnValue().Set( instance->PPublicKeyInfo() );
return;
}
Local<Function> callback = Local<Function>::Cast(info[1]);
const int argc = 1;
Local<Value> argv[argc] = { instance->PPublicKeyInfo() };
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
// String filename, Function callback (optional), Buffer password (optional), Number opsLimit (optional), Number r (optional), Number p (optional)
NAN_METHOD(KeyRing::Save){
PREPARE_FUNC_VARS();
MANDATORY_ARGS(1, "Mandatory args : String filename\nOptional args : Function callback");
if (instance->_keyType == "" || instance->_publicKey == 0 || instance->_privateKey == 0){ //Checking that a key is indeed defined. If not, throw an exception
Nan::ThrowTypeError("No key has been loaded into the keyring");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
String::Utf8Value filenameVal(info[0]);
string filename(*filenameVal);
if (info.Length() > 2){
if (info[2]->IsUndefined()){
Nan::ThrowTypeError("When using encryption, the password can't be null");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
Local<Value> passwordVal = info[2]->ToObject();
const unsigned char* password = (unsigned char*) Buffer::Data(passwordVal);
const size_t passwordSize = Buffer::Length(passwordVal);
if (info.Length() > 3){
//Additional scrypt parameters
unsigned long opsLimit = 16384;
unsigned short r = 8;
unsigned short p = 1;
if (info[3]->IsNumber()){
opsLimit = (unsigned long) info[3]->IntegerValue();
}
if (info.Length() > 4 && info[4]->IsNumber()){
r = (unsigned short) info[4]->Int32Value();
}
if (info.Length() > 5 && info[5]->IsNumber()){
p = (unsigned short) info[5]->Int32Value();
}
try {
saveKeyPair(filename, instance->_keyType, instance->_privateKey, instance->_publicKey, password, passwordSize, opsLimit, r, p);
} catch (runtime_error* e){
Nan::ThrowError(e->what());
info.GetReturnValue().Set(Nan::Undefined());
return;
} catch (void* e){
Nan::ThrowError("Error while saving the encrypted key file");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
} else {
try {
saveKeyPair(filename, instance->_keyType, instance->_privateKey, instance->_publicKey, password, passwordSize);
} catch (runtime_error* e){
Nan::ThrowError(e->what());
info.GetReturnValue().Set(Nan::Undefined());
return;
} catch (void* e){
Nan::ThrowError("Error while saving the encrypted key file");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
} else {
try {
saveKeyPair(filename, instance->_keyType, instance->_privateKey, instance->_publicKey);
} catch (runtime_error* e){
Nan::ThrowError(e->what());
info.GetReturnValue().Set(Nan::Undefined());
return;
} catch (void* e){
Nan::ThrowError("Error while saving the key file");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
if (info.Length() == 1 || (info.Length() > 1 && !info[1]->IsFunction())){
info.GetReturnValue().Set(Nan::Undefined());
return;
} else {
Local<Function> callback = Local<Function>::Cast(info[1]);
const int argc = 0;
Local<Value> argv[argc];
callback->Call(instance->globalObj, argc, argv);
info.GetReturnValue().Set(Nan::Undefined());
return;
}
}
NAN_METHOD(KeyRing::Clear){
Nan::HandleScope scope;
KeyRing* instance = ObjectWrap::Unwrap<KeyRing>(info.This());
if (instance->_privateKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_privateKey, crypto_sign_SECRETKEYBYTES);
else sodium_memzero(instance->_privateKey, crypto_box_SECRETKEYBYTES);
delete instance->_privateKey;
instance->_privateKey = 0;
}
if (instance->_publicKey != 0){
if (instance->_keyType == "ed25519") sodium_memzero(instance->_publicKey, crypto_sign_PUBLICKEYBYTES);
else sodium_memzero(instance->_publicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_publicKey;
instance->_publicKey = 0;
}
//Note : altKeys are always curve25519
if (instance->_altPrivateKey != 0){
sodium_memzero(instance->_altPrivateKey, crypto_box_SECRETKEYBYTES);
delete instance->_altPrivateKey;
instance->_altPrivateKey = 0;
}
if (instance->_altPublicKey != 0){
sodium_memzero(instance->_altPublicKey, crypto_box_PUBLICKEYBYTES);
delete instance->_altPublicKey;
instance->_altPublicKey = 0;
}
if (instance->_keyType != ""){
instance->_keyType = "";
}
instance->_filename = "";
info.GetReturnValue().Set(Nan::Undefined());
return;
}
NAN_METHOD(KeyRing::SetKeyBuffer){
Nan::HandleScope scope;
KeyRing* instance = ObjectWrap::Unwrap<KeyRing>(info.This());
MANDATORY_ARGS(1, "Mandatory args: Buffer keyBuffer");
if (info[0]->IsUndefined()){
Nan::ThrowTypeError("keyBuffer must be a buffer");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
const unsigned int c25519size = 5 + crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
const unsigned int ed25519size = 5 +crypto_sign_PUBLICKEYBYTES + crypto_sign_SECRETKEYBYTES;
string keyBuffer;
if (info[0]->IsString() || info[0]->IsStringObject()){
String::Utf8Value bufferVal(info[0]->ToString());
keyBuffer = string(*bufferVal);
} else { //Supposing it's a buffer
Local<Object> keyBufferVal = info[0]->ToObject();
const char* keyBufferChar = Buffer::Data(keyBufferVal);
const size_t keyBufferSize = Buffer::Length(keyBufferVal);
keyBuffer = string(keyBufferChar, keyBufferSize);
}
if (keyBuffer[0] == 0x05 && keyBuffer.length() != c25519size){
Nan::ThrowTypeError("Invalid key size for Curve25519 keypair");
info.GetReturnValue().Set(Nan::Undefined());
return;
} else if (keyBuffer[0] == 0x06 && keyBuffer.length() != ed25519size){
Nan::ThrowTypeError("Invalid key size for Ed25519 keypair");
info.GetReturnValue().Set(Nan::Undefined());
return;
} else if (!(keyBuffer[0] == 0x05 || keyBuffer[0] == 0x06)) {
Nan::ThrowTypeError("Invalid key type");
info.GetReturnValue().Set(Nan::Undefined());
return;
}
//Dynamic memory freeing and reallocation
if (instance->_privateKey != 0){
delete instance->_privateKey;
instance->_privateKey = 0;
}
if (instance->_publicKey != 0){
delete instance->_publicKey;
instance->_publicKey = 0;
}
if (instance->_keyType != "") instance->_keyType = "";
if (instance->_filename != "") instance->_filename = "";
if (keyBuffer[0] == 0x05){
instance->_keyType = "curve25519";
instance->_privateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
instance->_publicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
} else {
instance->_keyType = "ed25519";
instance->_privateKey = new unsigned char[crypto_sign_SECRETKEYBYTES];
instance->_publicKey = new unsigned char[crypto_sign_PUBLICKEYBYTES];
}
try {
decodeKeyBuffer(keyBuffer, &(instance->_keyType), instance->_privateKey, instance->_publicKey);
} catch (runtime_error* e){
Nan::ThrowTypeError(e->what());
info.GetReturnValue().Set(Nan::False());
return;
} catch (void* e){
Nan::ThrowTypeError("Unknown error while loading key buffer");
info.GetReturnValue().Set(Nan::False());
return;
}
if (instance->_keyType == "ed25519"){
instance->_altPublicKey = new unsigned char[crypto_box_PUBLICKEYBYTES];
instance->_altPrivateKey = new unsigned char[crypto_box_SECRETKEYBYTES];
deriveAltKeys(instance->_publicKey, instance->_privateKey, instance->_altPublicKey, instance->_altPrivateKey);
}
info.GetReturnValue().Set(Nan::True());
return;
}
NAN_METHOD(KeyRing::GetKeyBuffer){
PREPARE_FUNC_VARS();
if (instance->_keyLock){
info.GetReturnValue().Set(Nan::Undefined());
return;
}
if (!(instance->_privateKey != 0 && instance->_publicKey != 0)){
info.GetReturnValue().Set(Nan::Undefined());
return;
}
string keyBuffer = encodeKeyBuffer(instance->_keyType, instance->_privateKey, instance->_publicKey);
BUILD_BUFFER_STRING(keybuf, keyBuffer);
info.GetReturnValue().Set(keybuf);
return;
//return scope.Close(String::New(keyBuffer.c_str(), keyBuffer.length()));
}
NAN_METHOD(KeyRing::LockKeyBuffer){
Nan::HandleScope scope;
KeyRing* instance = ObjectWrap::Unwrap<KeyRing>(info.This());
instance->_keyLock = true;
info.GetReturnValue().Set(Nan::Undefined());
return;
}
string KeyRing::strToHex(string const& s){
static const char* const charset = "0123456789abcdef";
size_t length = s.length();
string output;
output.reserve(2 * length);
for (size_t i = 0; i < length; i++){
const unsigned char c = s[i];
output.push_back(charset[c >> 4]);
output.push_back(charset[c & 15]);
}
return output;
}
string KeyRing::hexToStr(string const& s){
static const char* const charset = "0123456789abcdef";
size_t length = s.length();
if (length & 1) throw invalid_argument("Odd length");
string output;
output.reserve(length / 2);
for (size_t i = 0; i < length; i+= 2){
char a = s[i];
const char* p = lower_bound(charset, charset + 16, a);
if (*p != a) throw invalid_argument("Invalid hex char");
char b = s[i + 1];
const char* q = lower_bound(charset, charset + 16, b);
if (*q != b) throw invalid_argument("Invalid hex char");
output.push_back(((p - charset) << 4) | (q - charset));
}
return output;
}
bool KeyRing::doesFileExist(string const& filename){
fstream file(filename.c_str(), ios::in);
bool isGood = file.good();
file.close();
return isGood;
}
void KeyRing::saveKeyPair(string const& filename, string const& keyType, const unsigned char* privateKey, const unsigned char* publicKey, const unsigned char* password, const size_t passwordSize, const unsigned long opsLimit, const unsigned int r, const unsigned int p){
fstream fileWriter(filename.c_str(), ios::out | ios::trunc);
/*string params[] = {"keyType", "privateKey", "publicKey"};
for (int i = 0; i < 3; i++){
if (!(keyPair->count(params[i]) > 0)) throw new runtime_error("Missing parameter when saving file : " + params[i]);
}*/
if (!((keyType == "ed25519" || keyType == "curve25519") && privateKey != 0 && publicKey != 0)) throw new runtime_error("Invalid parameters");
string keyBufferStr = encodeKeyBuffer(keyType, privateKey, publicKey);
//cout << "Key buffer: " << strToHex(keyBufferStr) << endl;
if (passwordSize > 0){
//cout << "Password has been provided" << endl;
//Write key type
if (keyType == "curve25519") fileWriter << (unsigned char) 0x05;
else fileWriter << (unsigned char) 0x06; //ed25519
//cout << "Type, " << endl;
//Write r (2bytes)
fileWriter << (unsigned char) (r >> 8);
fileWriter << (unsigned char) r;
//cout << "R, " << endl;
//Write p (2bytes)
fileWriter << (unsigned char) (p >> 8);
fileWriter << (unsigned char) p;
//cout << "P, " << endl;
//Write opsLimit (8bytes)
for (unsigned short i = 8; i > 0; i--){
fileWriter << (unsigned char) (opsLimit >> (8 * (i - 1)));
}
//cout << "OpsLimit" << endl;
//Write saltSize (2bytes)
unsigned short saltSize = 8;
//cout << "Salt size: " << saltSize << endl;
fileWriter << (unsigned char) (saltSize >> 8);
fileWriter << (unsigned char) saltSize;
//Write nonceSize (2bytes)
unsigned short nonceSize = crypto_secretbox_NONCEBYTES;
//cout << "Nonce size: " << nonceSize << endl;
fileWriter << (unsigned char) (nonceSize >> 8);