summaryrefslogtreecommitdiff
path: root/plugins/CryptoPP/src/cpp_rsam.cpp
blob: a356e7ad0a344d84ca7fd78f09dcc614c2048de6 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
#include "commonheaders.h"

///////////////////////////////////////////////////////////////////////////

#define RAND_SIZE (256/8)

RSA_EXPORT exports = {
    rsa_gen_keypair,
    rsa_get_keypair,
    rsa_get_keyhash,
    rsa_set_keypair,
    rsa_get_pubkey,
    rsa_set_pubkey,
    rsa_set_timeout,
    rsa_get_state,
    rsa_get_hash,
    rsa_connect,
    rsa_disconnect,
    rsa_disabled,
    rsa_recv,
    rsa_send,
    rsa_encrypt_file,
    rsa_decrypt_file,
    utf8encode,
    utf8decode,
    is_7bit_string,
    is_utf8_string,
    rsa_export_keypair,
    rsa_import_keypair,
    rsa_export_pubkey,
    rsa_import_pubkey
};

pRSA_IMPORT imp;

string null;
int timeout = 10;

const string priv_beg = "-----BEGIN SECUREIM PRIVATE KEY BLOCK-----";
const string priv_end = "-----END SECUREIM PRIVATE KEY BLOCK-----";

const string pub_beg = "-----BEGIN SECUREIM PUBLIC KEY BLOCK-----";
const string pub_end = "-----END SECUREIM PUBLIC KEY BLOCK-----";

const string crlf = "\x0D\x0A";

///////////////////////////////////////////////////////////////////////////


int __cdecl rsa_init(pRSA_EXPORT* e, pRSA_IMPORT i) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_init");
#endif
	*e = &exports;
	imp = i;
	if ( !hRSA4096 ) {
		// create context for private rsa keys
		hRSA4096 = (HANDLE) cpp_create_context(MODE_RSA_4096|MODE_PRIV_KEY);
		pCNTX tmp = (pCNTX) hRSA4096;
		pRSAPRIV p = new RSAPRIV;
		tmp->pdata = (PBYTE) p;
	}
	return 1;
}


int __cdecl rsa_done(void) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_done");
#endif
	if ( hRSA4096 ) {
		pCNTX tmp = (pCNTX) hRSA4096;
		pRSAPRIV p = (pRSAPRIV)tmp->pdata;
		delete p;
		tmp->pdata = 0;
		cpp_delete_context(hRSA4096);
		hRSA4096 = NULL;
	}

	return 1;
}


///////////////////////////////////////////////////////////////////////////


pRSAPRIV rsa_gen_keys(HANDLE context) {

	if ( context!=hRSA4096 ) return 0;

#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_gen_keys: %d", context);
#endif
	pCNTX ptr = get_context_on_id(context); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	string priv, pub;
	GenerateRSAKey(4096, priv, pub);

	StringSource privsrc(priv, true, NULL);
	RSAES_PKCS1v15_Decryptor Decryptor(privsrc);

	priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus() )) +
	       tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent() )) +
	       tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent() )) +
	       tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1() )) +
	       tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2() )) +
	       tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent() )) +
	       tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent() )) +
	       tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1() ));

	init_priv(r,priv);

	return r;
}


pRSAPRIV rsa_get_priv(pCNTX ptr) {
	pCNTX p = get_context_on_id(hRSA4096); if (!p) return 0;
	pRSAPRIV r = (pRSAPRIV) p->pdata;
	return r;
}


int __cdecl rsa_gen_keypair(short mode) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_gen_keypair: %d", mode);
#endif
	if ( mode&MODE_RSA_4096 ) rsa_gen_keys(hRSA4096); // 4096

	return 1;
}


int __cdecl rsa_get_keypair(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_get_keypair: %d", mode);
#endif
	pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	*privKeyLen = r->priv_k.length(); if ( privKey ) r->priv_k.copy((char*)privKey, *privKeyLen);
	*pubKeyLen = r->pub_k.length(); if ( pubKey ) r->pub_k.copy((char*)pubKey, *pubKeyLen);

	return 1;
}


int __cdecl rsa_get_keyhash(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_get_keyhash: %d", mode);
#endif
	pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	if ( privKey ) { *privKeyLen = r->priv_s.length(); r->priv_s.copy((char*)privKey, *privKeyLen); }
	if ( pubKey ) { *pubKeyLen = r->pub_s.length(); r->pub_s.copy((char*)pubKey, *pubKeyLen); }

	return 1;
}


int __cdecl rsa_set_keypair(short mode, PBYTE privKey, int privKeyLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_set_keypair: %s", privKey);
#endif
	pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	if ( privKey && privKeyLen ) {
	    string priv;
	    priv.assign((char*)privKey, privKeyLen);

	    if ( mode & MODE_RSA_BER ) {
		// old BER format
		StringStore s(priv);
		r->priv.BERDecode(s);

		RSAES_PKCS1v15_Decryptor Decryptor(r->priv);

		priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus() )) +
		       tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent() )) +
		       tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent() )) +
		       tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1() )) +
		       tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2() )) +
		       tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent() )) +
		       tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent() )) +
		       tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1() ));

	    }
	    init_priv(r,priv);
	}

	return 1;
}


int __cdecl rsa_get_pubkey(HANDLE context, PBYTE pubKey, int* pubKeyLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_get_pubkey: %s", pubKey);
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	*pubKeyLen = p->pub_k.length(); if ( pubKey ) p->pub_k.copy((char*)pubKey, *pubKeyLen);

	return 1;
}


int __cdecl rsa_set_pubkey(HANDLE context, PBYTE pubKey, int pubKeyLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_set_pubkey: %s", pubKey);
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	if ( pubKey && pubKeyLen ) {
	    string pub;
	    pub.assign((char*)pubKey, pubKeyLen);
	    init_pub(p,pub);
	}

	return 1;
}


void __cdecl rsa_set_timeout(int t) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_set_timeout: %d", t);
#endif
	timeout = t;
}


int __cdecl rsa_get_state(HANDLE context) {

	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	return p->state;
}


int __cdecl rsa_get_hash(PBYTE pubKey, int pubKeyLen, PBYTE pubHash, int* pubHashLen) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_get_hash: %d", pubKeyLen);
#endif
	string sig;
	sig = ::hash(pubKey, pubKeyLen);

	*pubHashLen = sig.length();
	if ( pubHash ) sig.copy((char*)pubHash, *pubHashLen);

	return 1;
}


int __cdecl rsa_connect(HANDLE context) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_connect: %08x", context);
#endif
	pCNTX ptr = get_context_on_id(context); if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state) return p->state;
	pRSAPRIV r = rsa_get_priv(ptr);

        if (ptr->mode&MODE_RSA_ONLY) {
		inject_msg(context,0x0D,tlv(0,0)+tlv(1,r->pub_k)+tlv(2,p->pub_s));
		p->state = 0x0D;
        }
        else {
		inject_msg(context,0x10,tlv(0,0)+tlv(1,r->pub_s)+tlv(2,p->pub_s));
		p->state = 2;
	}
	p->time = gettime()+timeout;

	return p->state;
}


int __cdecl rsa_disconnect(HANDLE context) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_disconnect: %08x", context);
#endif
	pCNTX ptr = get_context_on_id(context); if (!ptr) return 0;
	rsa_free( ptr ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé

	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); 
	if ( !p->state ) return 1;

	PBYTE buffer=(PBYTE) alloca(RAND_SIZE);
	GlobalRNG().GenerateBlock(buffer,RAND_SIZE);
	inject_msg(context,0xF0,encode_msg(0,p,::hash(buffer,RAND_SIZE)));

	p->state = 0;
	imp->rsa_notify(context,-3); // ñîåäèíåíèå ðàçîðâàíî âðó÷íóþ

	return 1;
}


int __cdecl rsa_disabled(HANDLE context) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_disabled: %08x", context);
#endif
	pCNTX ptr = get_context_on_id(context); if (!ptr) return 0;
	rsa_free( ptr ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé

	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); 
	p->state = 0;
	inject_msg(context,0xFF,null);
//	imp->rsa_notify(-context,-8); // ñîåäèíåíèå ðàçîðâàíî ïî ïðè÷èíå "disabled"
	return 1;
}


LPSTR __cdecl rsa_recv(HANDLE context, LPCSTR msg) {

#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_recv: %s", msg);
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);
	pRSAPRIV r = rsa_get_priv(ptr);

	rtrim(msg);

	string buf = base64decode(msg);
	if ( !buf.length() ) return 0;

	string data; int type;
	un_tlv(buf,type,data);
	if ( type==-1 ) return 0;

#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_recv: %02x %d", type, p->state);
#endif
	if ( type>0x10 && type<0xE0 )  // ïðîâåðèì òèï ñîîáùåíèÿ (êîãäà ñîåäèíåíèå åùå íå óñòàíîâëåíî)
	    if ( p->state==0 || p->state!=(type>>4) ) { // íåâåðíîå ñîñòîÿíèå
		// øëåì ïåðåðûâàíèå ñåññèè
		p->state=0; p->time=0;
		rsa_free( ptr ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé
		null_msg(context,0x00,-1); // ñåññèÿ ðàçîðâàíà ïî îøèáêå, íåâåðíûé òèï ñîîáùåíèÿ
		return 0;
	    }

	switch( type ) {

	case 0x00: // ïðåðûâàíèå ñåññèè ïî îøèáêå äðóãîé ñòîðîíîé
	{
	        // åñëè ñîåäèíåíèå óñòàíîâëåíî - íè÷åãî íå äåëàåì
		if ( p->state == 0 || p->state == 7 ) return 0;
		// èíà÷å ñáðàñûâàåì òåêóùåå ñîñòîÿíèå
		p->state=0; p->time=0;
		imp->rsa_notify(context,-2); // ñåññèÿ ðàçîðâàíà ïî îøèáêå äðóãîé ñòîðîíîé
	} break;

	// ýòî âñå áóäåì îáðàáàòûâàòü â îòäåëüíîì ïîòîêå, ÷òîáû èçáåæàòü òàéìàóòîâ
	case 0x10: // çàïðîñ íà óñòàíîâêó ñîåäèíåíèÿ
	case 0x22: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâëÿåì óæå êðèïòîêëþ÷
	case 0x23: // îòïðàâëÿåì ëîêàëüíûé ïàáëèê
	case 0x24: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâèì ëîêàëüíûé ïàáëèê
	case 0x33: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâëÿåì êðèïòîêëþ÷
	case 0x34:
	case 0x21: // ïîëó÷èëè êðèïòîêëþ÷, îòïðàâëÿåì êðèïòîòåñò
	case 0x32:
	case 0x40:
	case 0x0D: // çàïðîñ ïàáëèêà
	case 0xD0: // îòâåò ïàáëèêîì
	{
		if ( !p->event ) {
			p->event = CreateEvent(NULL,FALSE,FALSE,NULL);
			unsigned int tID;
			p->thread = (HANDLE) _beginthreadex(NULL, 0, sttConnectThread, (PVOID)context, 0, &tID);
#if defined(_DEBUG) || defined(NETLIB_LOG)
			Sent_NetLog("rsa_recv: _beginthreadex(sttConnectThread)");
#endif
		}
		EnterCriticalSection(&localQueueMutex);
		p->queue->push(tlv(type,data));
		LeaveCriticalSection(&localQueueMutex);
		SetEvent(p->event); // ñêàçàëè îáðàáàòûâàòü :)
	} break;

	case 0x50: // ïîëó÷èëè êðèïòîòåñò, îòïðàâëÿåì ñâîé êðèïòîòåñò
	{
		string msg = decode_msg(p,data);
		if ( !msg.length() ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		PBYTE buffer=(PBYTE) alloca(RAND_SIZE);
		GlobalRNG().GenerateBlock(buffer,RAND_SIZE);
        	inject_msg(context,0x60,encode_msg(0,p,::hash(buffer,RAND_SIZE)));
		p->state=7; p->time=0;
		rsa_free_thread( p ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé
		imp->rsa_notify(context,1);	// çàåáèñÿ, êðèïòîñåññèÿ óñòàíîâëåíà
	} break;

	case 0x60: // ïîëó÷èëè êðèïòîòåñò, ñåññèÿ óñòàíîâëåíà
	{
		string msg = decode_msg(p,data);
		if ( !msg.length() ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		p->state=7; p->time=0;
		rsa_free_thread( p ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé
		imp->rsa_notify(context,1);	// çàåáèñÿ, êðèïòîñåññèÿ óñòàíîâëåíà
	} break;

	case 0x70: // ïîëó÷èëè AES ñîîáùåíèå, äåêîäèðóåì
	{
		SAFE_FREE(ptr->tmp);
		string msg = decode_msg(p,data);
		if ( msg.length() ) {
			ptr->tmp = (LPSTR) _strdup(msg.c_str());
		}
		else {
			imp->rsa_notify(context,-5); // îøèáêà äåêîäèðîâàíèÿ AES ñîîáùåíèÿ
		}
		return ptr->tmp;
	} break;

	case 0xE0: // ïîëó÷èëè RSA ñîîáùåíèå, äåêîäèðóåì
	{
		SAFE_FREE(ptr->tmp);
		string msg = decode_rsa(p,r,data);
		if ( msg.length() ) {
			ptr->tmp = (LPSTR) _strdup(msg.c_str());
		}
		else {
			imp->rsa_notify(context,-6); // îøèáêà äåêîäèðîâàíèÿ RSA ñîîáùåíèÿ
		}
		return ptr->tmp;
	} break;

	case 0xF0: // ðàçðûâ ñîåäèíåíèÿ âðó÷íóþ
	{
		if ( p->state != 7 ) return 0;
		string msg = decode_msg(p,data);
		if ( !msg.length() ) return 0;
		p->state=0;
		rsa_free( ptr ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé
		imp->rsa_notify(context,-4); // ñîåäèíåíèå ðàçîðâàíî âðó÷íóþ äðóãîé ñòîðîíîé
	} break;

	case 0xFF: // ðàçðûâ ñîåäèíåíèÿ ïî ïðè÷èíå "disabled"
	{
		p->state=0;
		rsa_free( ptr ); // óäàëèì òðýä è î÷åðåäü ñîîáùåíèé
		imp->rsa_notify(context,-8); // ñîåäèíåíèå ðàçîðâàíî ïî ïðè÷èíå "disabled"
	} break;

	}

	if ( p->state != 0 && p->state != 7 )
		p->time = gettime() + timeout;

	return 0;
}

int __cdecl rsa_send(HANDLE context, LPCSTR msg) {

	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=0 && p->state!=7) return 0;

	if ( p->state == 7 ) // ñåññèÿ óñòàíîâëåíà, øèôðóåì AES è îòïðàâëÿåì
		inject_msg(context,0x70,encode_msg(1,p,string(msg)));
	else
	if ( p->state == 0 ) { // ñåññèÿ  óñòàíîâëåíà, îòïðàâëÿåì RSA ñîîáùåíèå
		if ( !p->pub_k.length() ) return 0;
		// åñòü ïàáëèê êëþ÷ - îòïðàâèì ñîîáùåíèå
		pRSAPRIV r = rsa_get_priv(ptr);
		inject_msg(context,0xE0,encode_rsa(1,p,r,string(msg)));
	}

	return 1;
}


void inject_msg(HANDLE context, int type, const string& msg) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("inject_msg(%02x): %s", type, msg.c_str());
#endif
	string txt=base64encode(tlv(type,msg));
	imp->rsa_inject(context,(LPCSTR)txt.c_str());
}


string encode_msg(short z, pRSADATA p, string& msg) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("encode_msg: %s", msg.c_str());
#endif
	string zlib = (z) ? cpp_zlibc(msg) : msg;
	string sig = ::hash(zlib);

	string ciphered;
	try {
		CBC_Mode<AES>::Encryption enc((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data());
		StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered));
		cbcEncryptor.Put((PBYTE)zlib.data(),zlib.length());
		cbcEncryptor.MessageEnd();
	}
	catch (...) {
		;
	}
	return tlv(z,ciphered)+tlv(2,sig);
}


string decode_msg(pRSADATA p, string& msg) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("decode_msg: %s", msg.c_str());
#endif
	string ciphered,sig; int t1,t2;
	un_tlv(msg,t1,ciphered);
	un_tlv(msg,t2,sig);

	string unciphered,zlib;
	try {
		CBC_Mode<AES>::Decryption dec((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data());
		StreamTransformationFilter cbcDecryptor(dec,new StringSink(zlib));
		cbcDecryptor.Put((PBYTE)ciphered.data(),ciphered.length());
		cbcDecryptor.MessageEnd();

		if ( sig == ::hash(zlib) ) {
			unciphered = (t1==1) ? cpp_zlibd(zlib) : zlib;
		}
	}
	catch (...) {
		;
	}
	return unciphered;
}


string encode_rsa(short z, pRSADATA p, pRSAPRIV r, string& msg) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("encode_rsa: %s", msg.c_str());
#endif
	string zlib = (z) ? cpp_zlibc(msg) : msg;

	string enc = RSAEncryptString(p->pub,zlib);
	string sig = RSASignString(r->priv,zlib);

	return tlv(z,enc)+tlv(2,sig);
}


string decode_rsa(pRSADATA p, pRSAPRIV r, string& msg) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("decode_rsa: %s", msg.c_str());
#endif
	string ciphered,sig; int t1,t2;
	un_tlv(msg,t1,ciphered);
	un_tlv(msg,t2,sig);

	string unciphered,zlib;
	zlib = RSADecryptString(r->priv,ciphered);
	if ( zlib.length() && RSAVerifyString(p->pub,zlib,sig) ) {
		unciphered = (t1==1) ? cpp_zlibd(zlib) : zlib;
	}
	return unciphered;
}


string gen_aes_key_iv(short m, pRSADATA p, pRSAPRIV r) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("gen_aes_key_iv: %04x", m);
#endif
	PBYTE buffer=(PBYTE) alloca(RAND_SIZE);

	GlobalRNG().GenerateBlock(buffer, RAND_SIZE);
	p->aes_k = hash256(buffer,RAND_SIZE);
	
	GlobalRNG().GenerateBlock(buffer, RAND_SIZE);
	p->aes_v = hash256(buffer,RAND_SIZE);

	string buf = tlv(10,p->aes_k)+tlv(11,p->aes_v);

	return encode_rsa(0,p,r,buf);
}


void init_priv(pRSAPRIV r, string& priv) {

	r->priv_k = priv;
	r->priv_s = ::hash(priv);

	int t;
	string tmp, n, e, d, p, q, dp, dq, u;

	while( priv.length() ) {
		un_tlv(priv,t,tmp);
		switch(t) {
		case 1: n = tmp; break;
		case 2: e = tmp; break;
		case 3: d = tmp; break;
		case 4: p = tmp; break;
		case 5: q = tmp; break;
		case 6: dp = tmp; break;
		case 7: dq = tmp; break;
		case 8: u = tmp; break;
		}
	}

	// if ( !empty );

	r->pub_k = tlv(1,n)+tlv(2,e);
	r->pub_s = ::hash(r->pub_k);

	r->priv.Initialize(BinaryToInteger(n),BinaryToInteger(e),
			   BinaryToInteger(d),BinaryToInteger(p),BinaryToInteger(q),
			   BinaryToInteger(dp),BinaryToInteger(dq),BinaryToInteger(u));
}


void init_pub(pRSADATA p, string& pub) {

	p->pub_k = pub;
	p->pub_s = ::hash(pub);

	int t;
	string tmp, n, e;

	while( pub.length() ) {
		un_tlv(pub,t,tmp);
		switch(t) {
		case 1: n = tmp; break;
		case 2: e = tmp; break;
		}
	}

	// if ( !empty );

	p->pub.Initialize(BinaryToInteger(n),BinaryToInteger(e));
}


void null_msg(HANDLE context, int type, int status) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("null_msg: %02x", status);
#endif
	inject_msg(context,type,null);
	imp->rsa_notify(context,status);
}


void rsa_timeout(HANDLE context, pRSADATA p) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_timeout");
#endif
	p->state=0; p->time=0;
//	null_msg(context,0x00,-7);
	imp->rsa_notify(context,-7); // ñåññèÿ ðàçîðâàíà ïî òàéìàóòó
}


int __cdecl rsa_encrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) {

	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=7) return 0;

	try {
		CBC_Mode<AES>::Encryption enc((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data());
		FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (enc,new FileSink(file_out)));
		delete f;
	}
	catch (...) {
		return 0;
	}
	return 1;
}


int __cdecl rsa_decrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) {

	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=7) return 0;

	try {
		CBC_Mode<AES>::Decryption dec((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data());
		FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (dec,new FileSink(file_out)));
		delete f;
	}
	catch (...) {
		return 0;
	}
	return 1;
}


int __cdecl rsa_recv_thread(HANDLE context, string& msg) {

#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_recv_thread: %s", msg.c_str());
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);
	pRSAPRIV r = rsa_get_priv(ptr);

	string data; int type;
	un_tlv(msg,type,data);
	if ( type==-1 ) return 0;

#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_recv_thread: %02x %d", type, p->state);
#endif
	int t[4];

	switch( type ) {

	case 0x10:
	{
		int features; string sha1,sha2;
		un_tlv(un_tlv(un_tlv(data,t[0],features),t[1],sha1),t[2],sha2);
		BOOL lr = (p->pub_s==sha1); BOOL ll = (r->pub_s==sha2);
		switch( (lr<<4)|ll ) {
		case 0x11: { // îáà ïàáëèêà ñîâïàëè
			inject_msg(context,0x21,gen_aes_key_iv(ptr->mode,p,r));
			p->state=5;
		} break;
		case 0x10: { // ñîâïàë óäàëåííûé ïàáëèê, íóæåí ëîêàëüíûé
			inject_msg(context,0x22,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,r->pub_s));
			p->state=3;
		} break;
		case 0x01: { // ñîâïàë ëîêàëüíûé ïàáëèê, íóæåí óäàëåííûé
			inject_msg(context,0x23,tlv(0,features));
			p->state=3;
		} break;
		case 0x00: { // íå ñîâïàëè îáà ïàáëèêà
			inject_msg(context,0x24,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,r->pub_s));
			p->state=3;
		} break;
		}
	} break;

	case 0x22: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâëÿåì óæå êðèïòîêëþ÷
	{
		int features; string pub;
		un_tlv(un_tlv(data,t[0],features),t[1],pub);
		string sig = ::hash(pub);
		if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(),pub.length(),(PBYTE)sig.data(),sig.length()) ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		init_pub(p,pub);
		if ( p->state==0 ) { // timeout
//			rsa_connect(context);
			return -1;
		}
		inject_msg(context,0x32,gen_aes_key_iv(ptr->mode,p,r));
		p->state=5;
	} break;

	case 0x23: // îòïðàâëÿåì ëîêàëüíûé ïàáëèê
	{
		int features;
		un_tlv(data,t[0],features);
		inject_msg(context,0x33,tlv(1,r->pub_k)+tlv(2,r->pub_s));
		p->state=4;
	} break;

	case 0x24: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâèì ëîêàëüíûé ïàáëèê
	{
		int features; string pub;
		un_tlv(un_tlv(data,t[0],features),t[1],pub);
		string sig = ::hash(pub);
		if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(),pub.length(),(PBYTE)sig.data(),sig.length()) ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		init_pub(p,pub);
		if ( p->state==0 ) { // timeout
//			rsa_connect(context);
			return -1;
		}
		inject_msg(context,0x34,tlv(1,r->pub_k)+tlv(2,r->pub_s));
		p->state=4;
	} break;

	case 0x33: // ïîëó÷èëè óäàëåííûé ïàáëèê, îòïðàâëÿåì êðèïòîêëþ÷
	case 0x34:
	{
		string pub;
		un_tlv(data,t[0],pub);
		string sig = ::hash(pub);
		if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(),pub.length(),(PBYTE)sig.data(),sig.length()) ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		init_pub(p,pub);
		if ( p->state==0 ) { // timeout
//			rsa_connect(context);
			return -1;
		}
		inject_msg(context,0x40,gen_aes_key_iv(ptr->mode,p,r));
		p->state=5;
	} break;

	case 0x21: // ïîëó÷èëè êðèïòîêëþ÷, îòïðàâëÿåì êðèïòîòåñò
	case 0x32:
	case 0x40:
	{
		string key = decode_rsa(p,r,data);
		if ( !key.length() ) {
			p->state=0; p->time=0;
			null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
			return 0;
		}
		un_tlv(key,t[0],p->aes_k);
		un_tlv(key,t[1],p->aes_v);
		PBYTE buffer=(PBYTE) alloca(RAND_SIZE);
		GlobalRNG().GenerateBlock(buffer,RAND_SIZE);
		inject_msg(context,0x50,encode_msg(0, p, ::hash(buffer,RAND_SIZE)));
		p->state=6;
	} break;

	case 0x0D: // çàïðîñ ïàáëèêà
	case 0xD0: // îòâåò ïàáëèêîì
	{
		int features; string pub,sha;
		un_tlv(un_tlv(un_tlv(data,t[0],features),t[1],pub),t[2],sha);
		if ( p->pub_k!=pub ) { // ïðèøåë íîâûé ïàáëèê
			string sig = ::hash(pub);
			if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(),pub.length(),(PBYTE)sig.data(),sig.length()) ) {
				p->state=0; p->time=0;
				null_msg(context,0x00,-type); // ñåññèÿ ðàçîðâàíà ïî îøèáêå
				return 0;
			}
			init_pub(p,pub);
		}
		if ( type == 0x0D ) { // íóæíî îòïðàâèòü ìîé ïàáëèê
			inject_msg(context,0xD0,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,p->pub_s));
		}
		p->state=0; p->time=0;
	} break;

	}

	if ( p->state != 0 && p->state != 7 )
		p->time = gettime() + timeout;

	return 1;
}


void rsa_alloc( pCNTX ptr ) {
	pRSADATA p = new RSADATA;
	p->state = 0;
	p->time = 0;
	p->thread = p->event = NULL;
	p->thread_exit = 0;
	p->queue = new STRINGQUEUE;
	ptr->pdata = (PBYTE) p;
}


void rsa_free( pCNTX ptr ) {
	pRSADATA p = (pRSADATA) ptr->pdata;
	if (p == NULL)
		return;

	if (p->event) {
		p->thread_exit = 2; // îòïóñêàåì ïîòîê â ñâîáîäíîå ïëàâàíèå
		SetEvent( p->event );
	}
	
	delete p->queue;
	delete p;
	ptr->pdata = NULL;
}

void rsa_free_thread( pRSADATA p ) {
	if ( p->event ) {
		p->thread_exit = 1;
		SetEvent( p->event );
		// æäåì çàâåðøåíèÿ ïîòîêà
		WaitForSingleObject(p->thread, INFINITE);
		CloseHandle( p->thread );
		CloseHandle( p->event );
		p->thread = p->event = NULL;
		p->thread_exit = 0;
	}
	p->time = 0;
	clear_queue( p );
}


void clear_queue( pRSADATA p ) {
	EnterCriticalSection(&localQueueMutex);
	while( p->queue && !p->queue->empty() ) {
       		p->queue->pop();
	}
	LeaveCriticalSection(&localQueueMutex);
}


// establish RSA/AES thread
unsigned __stdcall sttConnectThread( LPVOID arg ) {

	HANDLE context = (HANDLE) arg;

	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	while(1) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
		Sent_NetLog("sttConnectThread: WaitForSingleObject");
#endif
		WaitForSingleObject(p->event, INFINITE); // dwMsec rc==WAIT_TIMEOUT
		if ( p->thread_exit == 1 ) return 0;
		if ( p->thread_exit == 2 ) {
			// ìû â ñâîáîäíîì ïëàâàíèè - îñâîáîäèì ïàìÿòü è çàâåðøèì òðýä
			CloseHandle( p->thread );
			CloseHandle( p->event );
			SAFE_DELETE(p->queue);
			SAFE_DELETE(p);
			return 0;
		}
		// äîæäàëèñü ñîîáùåíèÿ â î÷åðåäè
		while( !p->thread_exit && p->queue && !p->queue->empty() ) {
			// îáðàáîòàåì ñîîáùåíèÿ èç î÷åðåäè
			if ( rsa_recv_thread(context, p->queue->front()) == -1 ) {
				// î÷èñòèòü î÷åðåäü
				clear_queue(p);
				break;
			}
			EnterCriticalSection(&localQueueMutex);
			p->queue->pop();
			LeaveCriticalSection(&localQueueMutex);
		}
	}
}


int __cdecl rsa_export_keypair(short mode, LPSTR privKey, LPSTR pubKey, LPSTR passPhrase) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_export_keypair: %d", mode);
#endif
	pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	if ( pubKey ) {
		string pub;
		pub = tlv(3,r->pub_k) + tlv(4,r->pub_s);
		pub = pub_beg + crlf + add_delim(base64encode(pub),crlf,65) + pub_end + crlf;
		strcpy(pubKey, pub.c_str());
	}

	if ( privKey && passPhrase ) {
		string key = hash256(passPhrase);
		string iv = hash256(key);
		string priv = pad256(r->priv_k);

		string ciphered;
		try {
			CBC_Mode<AES>::Encryption enc((PBYTE)key.data(),key.length(),(PBYTE)iv.data());
			StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered));
			cbcEncryptor.Put((PBYTE)priv.data(),priv.length());
			cbcEncryptor.MessageEnd();
		}
		catch (...) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
			Sent_NetLog("rsa_export_keypair: error bad_passphrase");
#endif
			return 0;
		}
		
		priv = tlv(1,ciphered) + tlv(2,::hash(ciphered));
		priv = priv_beg + crlf + add_delim(base64encode(priv),crlf,65) + priv_end + crlf;

		strcpy(privKey, priv.c_str());
	}

	return 1;
}


int __cdecl rsa_import_keypair(short mode, LPSTR privKey, LPSTR passPhrase) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_import_keypair: %d", mode);
#endif
	pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0;
	pRSAPRIV r = (pRSAPRIV) ptr->pdata;

	if ( !passPhrase ) return 0;

	string priv;
	u_int found;

	priv.assign(privKey);
	del_delim(priv,crlf);

	found = priv.find(priv_beg);
	if ( found != string::npos ) {
	    priv = priv.substr(found+priv_beg.length());
	    found = priv.find(priv_end);
	    if ( found != string::npos ) {
		priv = base64decode(priv.substr(0,found));
		TLV k(priv);
		if ( k.exist(1) && k.exist(2) && ::hash(k.get(1)) == k.get(2) ) {
		    priv = k.get(1);
		    
		    string key = hash256(passPhrase);
		    string iv = hash256(key);

		    string unciphered;
		    try {
			CBC_Mode<AES>::Decryption dec((PBYTE)key.data(),key.length(),(PBYTE)iv.data());
			StreamTransformationFilter cbcDecryptor(dec,new StringSink(unciphered));
			cbcDecryptor.Put((PBYTE)priv.data(),priv.length());
			cbcDecryptor.MessageEnd();
		    }
		    catch (...)	{
#if defined(_DEBUG) || defined(NETLIB_LOG)
			Sent_NetLog("rsa_import_keypair: error bad_passphrase");
#endif
			return 0;
		    }

		    init_priv(r,unciphered);
		    return 1;
		}
	    }
	}

	return 0;
}


int __cdecl rsa_export_pubkey(HANDLE context, LPSTR pubKey) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_export_pubkey: %08x", context);
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	if ( !p->pub_k.length() || !pubKey ) return 0;

	string pub;
	pub = tlv(3,p->pub_k) + tlv(4,p->pub_s);
	pub = pub_beg + crlf + add_delim(base64encode(pub),crlf,65) + pub_end + crlf;
	strcpy(pubKey, pub.c_str());

	return 1;
}


int __cdecl rsa_import_pubkey(HANDLE context, LPSTR pubKey) {
#if defined(_DEBUG) || defined(NETLIB_LOG)
	Sent_NetLog("rsa_import_pubkey: %08x", context);
#endif
	pCNTX ptr = get_context_on_id(context);	if (!ptr) return 0;
	pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr);

	if ( !pubKey ) return 0;

	string pub;
	u_int found;

	pub.assign(pubKey);
	del_delim(pub,crlf);

	found = pub.find(pub_beg);
	if ( found != string::npos ) {
	    pub = pub.substr(found+pub_beg.length());
	    found = pub.find(pub_end);
	    if ( found != string::npos ) {
		pub = base64decode(pub.substr(0,found));
		TLV k(pub);
		if ( k.exist(3) && k.exist(4) && ::hash(k.get(3)) == k.get(4) ) {
		    init_pub(p,k.get(3));
		    return 1;
		}
	    }	
	}	
	return 0;
}


// EOF