-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathLbRSA.pas
1660 lines (1512 loc) · 55 KB
/
LbRSA.pas
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
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower LockBox
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Sebastian Zierer, Jarto Tarpio
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* LBRSA.PAS 2.09 *}
{* Copyright (c) 2002 TurboPower Software Co *}
{* All rights reserved. *}
{*********************************************************}
{$I LockBox.inc}
unit LbRSA;
{-RSA encryption and signature components, classes, and routines}
interface
uses
{$IFNDEF FPC}
Windows,
{$ENDIF}
{$IFDEF POSIX}
Types,
{$ENDIF}
Classes,
SysUtils,
LbBigInt,
LbAsym,
LbCipher,
LbConst;
const
{ cipher block size constants } {!!.02}
cRSAMinPadBytes = 11;
cRSACipherBlockSize : array[TLbAsymKeySize] of Word =
(cBytes128, cBytes256, cBytes512, cBytes768, cBytes1024,
cBytes2048, cBytes3072);
cRSAPlainBlockSize : array[TLbAsymKeySize] of Word =
(cBytes128-cRSAMinPadBytes, cBytes256-cRSAMinPadBytes,
cBytes512-cRSAMinPadBytes, cBytes768-cRSAMinPadBytes,
cBytes1024-cRSAMinPadBytes, cBytes2048-cRSAMinPadBytes,
cBytes3072-cRSAMinPadBytes);
type
{ ciphertext block types } {!!.02}
PRSACipherBlock128 = ^TRSACipherBlock128;
TRSACipherBlock128 = array[0..cBytes128-1] of Byte;
PRSACipherBlock256 = ^TRSACipherBlock256;
TRSACipherBlock256 = array[0..cBytes256-1] of Byte;
PRSACipherBlock512 = ^TRSACipherBlock512;
TRSACipherBlock512 = array[0..cBytes512-1] of Byte;
PRSACipherBlock768 = ^TRSACipherBlock768;
TRSACipherBlock768 = array[0..cBytes768-1] of Byte;
PRSACipherBlock1024 = ^TRSACipherBlock1024;
TRSACipherBlock1024 = array[0..cBytes1024-1] of Byte;
PRSACipherBlock2048 = ^TRSACipherBlock2048;
TRSACipherBlock2048 = array[0..cBytes2048-1] of Byte;
PRSACipherBlock3072 = ^TRSACipherBlock3072;
TRSACipherBlock3072 = array[0..cBytes3072-1] of Byte;
{ plaintext block types } {!!.02}
PRSAPlainBlock128 = ^TRSAPlainBlock128;
TRSAPlainBlock128 = array[0..cBytes128-12] of Byte;
PRSAPlainBlock256 = ^TRSAPlainBlock256;
TRSAPlainBlock256 = array[0..cBytes256-12] of Byte;
PRSAPlainBlock512 = ^TRSAPlainBlock512;
TRSAPlainBlock512 = array[0..cBytes512-12] of Byte;
PRSAPlainBlock768 = ^TRSAPlainBlock768;
TRSAPlainBlock768 = array[0..cBytes768-12] of Byte;
PRSAPlainBlock1024 = ^TRSAPlainBlock1024;
TRSAPlainBlock1024 = array[0..cBytes1024-12] of Byte;
PRSAPlainBlock2048 = ^TRSAPlainBlock2048;
TRSAPlainBlock2048 = array[0..cBytes2048-12] of Byte;
PRSAPlainBlock3072 = ^TRSAPlainBlock3072;
TRSAPlainBlock3072 = array[0..cBytes3072-12] of Byte;
{ default block type }
TRSAPlainBlock = TRSAPlainBlock512;
TRSACipherBlock = TRSACipherBlock512;
{ signature types }
TRSASignatureBlock = array[0..cBytes3072-1] of Byte;
TRSAHashMethod = (hmMD5, hmSHA1);
type
TLbRSAGetSignatureEvent = procedure(Sender : TObject;
var Sig : TRSASignatureBlock) of object;
TLbRSACallback = procedure(var Abort : Boolean) of object;
{ TLbRSAKey }
type
TLbRSAKey = class(TLbAsymmetricKey)
protected {private}
FModulus : TLbBigInt;
FExponent : TLbBigInt;
function ParseASNKey(Input : pByte; Length : Integer) : boolean; override;
function CreateASNKey(Input : pByteArray; Length : Integer) : Integer; override;
function GetModulusAsHexString : string;
procedure SetModulusAsHexString(Value : string);
function GetExponentAsHexString : string;
procedure SetExponentAsHexString(Value : string);
public
constructor Create(aKeySize : TLbAsymKeySize); override;
destructor Destroy; override;
procedure Assign(aKey : TLbAsymmetricKey); override;
procedure Clear;
property Modulus : TLbBigInt read FModulus;
property ModulusAsString : string read GetModulusAsHexString write SetModulusAsHexString;
property Exponent : TLbBigInt read FExponent;
property ExponentAsString : string read GetExponentAsHexString write SetExponentAsHexString;
end;
{ TLbRSA }
type
TLbRSA = class(TLbAsymmetricCipher)
private
function GetCryptoServiceProviderXML(AIsForPrivateKey : Boolean) : String;
function CalculatePQ : Boolean;
function GetOpenSSLText(AIsForPrivateKey: Boolean): String;
protected {private}
FPrivateKey : TLbRSAKey;
FPublicKey : TLbRSAKey;
FPrimeTestIterations : Byte;
FFirstPrime : TLbBigInt;
FSecondPrime : TLbBigInt;
procedure SetKeySize(Value : TLbAsymKeySize); override;
public {methods}
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure DecryptFile(const InFile, OutFile : string); override;
procedure DecryptStream(InStream , OutStream : TStream); override;
function DecryptString(const InString : RawByteString) : RawByteString; override;
procedure EncryptFile(const InFile, OutFile : string); override;
procedure EncryptStream(InStream, OutStream : TStream); override;
function EncryptString(const InString : RawByteString) : RawByteString; override;
procedure GenerateKeyPair; override;
procedure GenerateKeyPairWithExponent(AExponent : TLbBigInt);
function OutBufSizeNeeded(InBufSize : Cardinal) : Cardinal; override;
procedure RSACallback(var Abort : Boolean);
property PrivateKey : TLbRSAKey read FPrivateKey;
property PublicKey : TLbRSAKey read FPublicKey;
property CryptoServiceProviderXML[AIsForPrivateKey : Boolean] : String read GetCryptoServiceProviderXML;
property OpenSSLText[AIsForPrivateKey : Boolean] : String read GetOpenSSLText;
published {properties}
property PrimeTestIterations : Byte read FPrimeTestIterations write FPrimeTestIterations;
property KeySize;
published {events}
property OnProgress;
end;
{ TLbRSASSA }
type
TLbRSASSA = class(TLbSignature)
protected {private}
FPrivateKey : TLbRSAKey;
FPublicKey : TLbRSAKey;
FHashMethod : TRSAHashMethod;
FPrimeTestIterations : Byte;
FSignature : TLbBigInt;
FOnGetSignature : TLbRSAGetSignatureEvent;
procedure DoGetSignature;
procedure EncryptHash(const HashDigest; DigestLen : Cardinal; WithHashDigestInfo : Boolean);
procedure DecryptHash(var HashDigest; DigestLen : Cardinal; WithHashDigestInfo : Boolean);
procedure RSACallback(var Abort : Boolean);
procedure SetKeySize(Value : TLbAsymKeySize); override;
function GetHashIdentifier : String;
public {methods}
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure GenerateKeyPair; override;
procedure SignBuffer(const Buf; BufLen : Cardinal); overload; override;
procedure SignFile(const AFileName : string); overload; override;
procedure SignStream(AStream : TStream); overload; override;
procedure SignString(const AStr : RawByteString); overload; override;
procedure SignBuffer(const Buf; BufLen : Cardinal; WithHashDigestInfo : Boolean); reintroduce; overload;
procedure SignFile(const AFileName : string; WithHashDigestInfo : Boolean); reintroduce; overload;
procedure SignStream(AStream : TStream; WithHashDigestInfo : Boolean); reintroduce; overload;
procedure SignString(const AStr : RawByteString; WithHashDigestInfo : Boolean); reintroduce; overload;
function VerifyBuffer(const Buf; BufLen : Cardinal) : Boolean; overload; override;
function VerifyFile(const AFileName : string) : Boolean; overload; override;
function VerifyStream(AStream : TStream) : Boolean; overload; override;
function VerifyString(const AStr : RawByteString) : Boolean; overload; override;
function VerifyBuffer(const Buf; BufLen : Cardinal; WithHashDigestInfo : Boolean) : Boolean; reintroduce; overload;
function VerifyFile(const AFileName : string; WithHashDigestInfo : Boolean) : Boolean; reintroduce; overload;
function VerifyStream(AStream : TStream; WithHashDigestInfo : Boolean) : Boolean; reintroduce; overload;
function VerifyString(const AStr : RawByteString; WithHashDigestInfo : Boolean) : Boolean; reintroduce; overload;
public {properties}
property PrivateKey : TLbRSAKey
read FPrivateKey;
property PublicKey : TLbRSAKey
read FPublicKey;
property Signature : TLbBigInt
read FSignature;
published {properties}
property HashMethod : TRSAHashMethod
read FHashMethod write FHashMethod;
property PrimeTestIterations : Byte
read FPrimeTestIterations write FPrimeTestIterations;
property KeySize;
published {events}
property OnGetSignature : TLbRSAGetSignatureEvent
read FOnGetSignature write FOnGetSignature;
property OnProgress;
end;
{ low level RSA cipher public routines }
{ new public routines } {!!.02}
function EncryptRSAEx(PublicKey : TLbRSAKey; pInBlock, pOutBlock : PByteArray;
InDataSize : Integer) : Longint;
function DecryptRSAEx(PrivateKey : TLbRSAKey;
pInBlock, pOutBlock : PByteArray) : Longint;
function EncryptRSA128(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock128;
var OutBlock : TRSACipherBlock128) : Longint;
function DecryptRSA128(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock128;
var OutBlock : TRSAPlainBlock128) : Longint;
function EncryptRSA256(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock256;
var OutBlock : TRSACipherBlock256) : Longint;
function DecryptRSA256(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock256;
var OutBlock : TRSAPlainBlock256) : Longint;
function EncryptRSA512(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock512;
var OutBlock : TRSACipherBlock512) : Longint;
function DecryptRSA512(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock512;
var OutBlock : TRSAPlainBlock512) : Longint;
function EncryptRSA768(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock768;
var OutBlock : TRSACipherBlock768) : Longint;
function DecryptRSA768(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock768;
var OutBlock : TRSAPlainBlock768) : Longint;
function EncryptRSA1024(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock1024;
var OutBlock : TRSACipherBlock1024) : Longint;
function DecryptRSA1024(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock1024;
var OutBlock : TRSAPlainBlock1024) : Longint;
function EncryptRSA2048(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock2048;
var OutBlock : TRSACipherBlock2048) : Longint;
function DecryptRSA2048(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock2048;
var OutBlock : TRSAPlainBlock2048) : Longint;
function EncryptRSA3072(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock3072;
var OutBlock : TRSACipherBlock3072) : Longint;
function DecryptRSA3072(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock3072;
var OutBlock : TRSAPlainBlock3072) : Longint;
{!!.02}
function EncryptRSA(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock;
var OutBlock : TRSACipherBlock) : Longint;
function DecryptRSA(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock;
var OutBlock : TRSAPlainBlock) : Longint;
procedure RSAEncryptFile(const InFile, OutFile : string;
Key : TLbRSAKey; Encrypt : Boolean);
procedure RSAEncryptStream(InStream, OutStream : TStream;
Key : TLbRSAKey; Encrypt : Boolean);
function RSAEncryptString(const InString : RawByteString;
Key : TLbRSAKey; Encrypt : Boolean) : RawByteString;
procedure GenerateRSAKeysEx(var PrivateKey, PublicKey : TLbRSAKey;
KeySize : TLbAsymKeySize; PrimeTestIterations : Byte;
Exponent : TlbBigInt; Callback : TLbRSACallback);
procedure GenerateRSAKeys(var PrivateKey, PublicKey : TLbRSAKey); overload;
procedure GenerateRSAKeys(Exponent : TlbBigInt; var PrivateKey, PublicKey : TLbRSAKey); overload;
implementation
uses
LbUtils, LbString, LbProc;
const
cDefHashMethod = hmMD5;
type
TRSABlockType = (bt00, bt01, bt02);
{ == Local RSA routines ==================================================== }
procedure RSADecodeBlock(biBlock : TLbBigInt);
var
i : DWord;
Buf : TRSAPlainBlock3072;
begin
{ verify block format }
i := biBlock.Size;
if (i < cRSAMinPadBytes) then
raise Exception.Create(sRSADecodingErrBTS);
if (i > cBytes3072) then
raise Exception.Create(sRSADecodingErrBTL);
if (biBlock.GetByteValue(i) <> Byte(bt01)) and (biBlock.GetByteValue(i) <> Byte(bt02)) then
raise Exception.Create(sRSADecodingErrIBT);
Dec(i);
{ count padding bytes }
while (biBlock.GetByteValue(i) <> 0) do begin
Dec(i);
if (i <= 0) then
raise Exception.Create(sRSADecodingErrIBF);
end;
{ strip off padding bytes }
biBlock.ToBuffer(Buf, i-1);
biBlock.CopyBuffer(Buf, i-1);
end;
{ -------------------------------------------------------------------------- }
procedure RSAFormatBlock(biBlock : TLbBigInt; BlockType : TRSABlockType);
begin
if (biBlock.Int.IntBuf.dwLen - biBlock.Int.dwUsed) < 11 then {!!.02}
raise Exception.Create(sRSAEncodingErr); {!!.02}
{ separate data from padding }
biBlock.AppendByte($00);
{ append padding }
while (biBlock.Int.IntBuf.dwLen - biBlock.Int.dwUsed) > 2 do begin {!!.02}
if (BlockType = bt01) then
biBlock.AppendByte(Byte($FF))
else
biBlock.AppendByte(Byte(Random($FD) + 1));
end;
{ append tag }
if (BlockType = bt01) then
biBlock.AppendByte($01)
else
biBlock.AppendByte($02);
{ last byte always 0 }
biBlock.AppendByte($00);
end;
{ -------------------------------------------------------------------------- }
procedure RSAEncryptBigInt(biBlock : TLbBigInt; Key : TLbRSAKey;
BlockType : TRSABlockType; Encrypt : Boolean);
var
dwSize, dwLen : DWORD;
tmp1, tmp2 : TLbBigInt;
begin
tmp1 := TLbBigInt.Create(cLbAsymKeyBytes[Key.KeySize]);
tmp2 := TLbBigInt.Create(cLbAsymKeyBytes[Key.KeySize]);
try
if Encrypt then
RSAFormatBlock(biBlock, BlockType);
tmp1.Copy(biBlock);
dwSize := tmp1.Size;
biBlock.Clear;
repeat
dwLen := Min(dwSize, Key.Modulus.Size);
tmp2.CopyLen(tmp1, dwLen);
tmp2.PowerAndMod(Key.Exponent, Key.Modulus);
biBlock.Append(tmp2);
tmp1.Shr_(dwLen * 8);
dwSize := dwSize - dwLen;
until (dwSize <= 0);
if Encrypt then {!!.02}
{ replace leading zeros that were trimmed in the math } {!!.02}
while (biBlock.Size < cLbAsymKeyBytes[Key.KeySize]) do {!!.02}
biBlock.AppendByte($00) {!!.02}
else {!!.02}
RSADecodeBlock(biBlock);
finally
tmp1.Free;
tmp2.Free;
end;
end;
{ == Public RSA routines =================================================== }
procedure GenerateRSAKeys(Exponent : TLbBigInt; var PrivateKey, PublicKey : TLbRSAKey);
{ create RSA public/private key pair with default settings }
begin
GenerateRSAKeysEx(PrivateKey, PublicKey, cLbDefAsymKeySize, cDefIterations, Exponent, nil);
end;
{ -------------------------------------------------------------------------- }
procedure GenerateRSAKeys(var PrivateKey, PublicKey : TLbRSAKey);
begin
GenerateRSAKeys(nil, PrivateKey, PublicKey);
end;
{ -------------------------------------------------------------------------- }
procedure GenerateRSAKeysEx(var PrivateKey, PublicKey : TLbRSAKey;
KeySize : TLbAsymKeySize;
PrimeTestIterations : Byte;
Exponent : TlbBigInt;
Callback : TLbRSACallback);
{ create RSA key pair speciying size and prime test iterations and }
{ callback function }
var
q : TLbBigInt;
p : TLbBigInt;
p1q1 : TLbBigInt;
d : TLbBigInt;
e : TLbBigInt;
n : TLbBigInt;
Abort : Boolean;
begin
PrivateKey := TLbRSAKey.Create(KeySize);
PublicKey := TLbRSAKey.Create(KeySize);
{ create temp variables }
p1q1 := TLbBigInt.Create(cLbAsymKeyBytes[KeySize]);
d := TLbBigInt.Create(cLbAsymKeyBytes[KeySize]);
e := TLbBigInt.Create(cLbAsymKeyBytes[KeySize]);
n := TLbBigInt.Create(cLbAsymKeyBytes[KeySize]);
p := TLbBigInt.Create(cLbAsymKeyBytes[KeySize] div 2);
q := TLbBigInt.Create(cLbAsymKeyBytes[KeySize] div 2);
try
Abort := False;
repeat
{ p , q = random primes }
repeat
p.RandomPrime(PrimeTestIterations);
{ check for abort }
if Assigned(Callback) then
Callback(Abort);
if Abort then
Exit;
q.RandomPrime(PrimeTestIterations);
{ check for abort }
if Assigned(Callback) then
Callback(Abort);
if Abort then
Exit;
until (p.Compare(q) <> 0);
{ n = pq }
n.Copy(p);
n.Multiply(q);
{ p1q1 = (p-1)(q-1) }
p.SubtractByte($01);
q.SubtractByte($01);
p1q1.Copy(p);
p1q1.Multiply(q);
if assigned(Exponent) then
begin
e.Copy(Exponent);
end
else
begin
{ e = randomly chosen simple prime > 3 }
e.RandomSimplePrime;
end;
{ d = inverse(e) mod (p-1)(q-1) }
d.Copy(e);
until d.ModInv(p1q1);
{ assign n and d to private key }
PrivateKey.Modulus.Copy(n);
PrivateKey.Exponent.Copy(d);
{ assign n and e to public key }
PublicKey.Modulus.Copy(n);
PublicKey.Exponent.Copy(e);
finally
p1q1.Free;
d.Free;
e.Free;
n.Free;
p.Free;
q.Free;
end;
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSAEx(PublicKey : TLbRSAKey;
pInBlock, pOutBlock : PByteArray;
InDataSize : Integer) : Longint;
{ IMPORTANT: verify block sizes before calling this routine }
var
biBlock : TLbBigInt;
OutSize : DWord;
begin
OutSize := cRSACipherBlockSize[PublicKey.KeySize];
biBlock := TLbBigInt.Create(OutSize);
try
biBlock.CopyBuffer(pInBlock^, InDataSize);
RSAEncryptBigInt(biBlock, PublicKey, bt02, True);
if Integer(OutSize) < biBlock.Size then {!!.05}
raise Exception.Create('OutBlock size too small');
biBlock.ToBuffer(pOutBlock^, biBlock.Size);
finally
Result := biBlock.Size;
biBlock.Free;
end;
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSAEx(PrivateKey : TLbRSAKey;
pInBlock, pOutBlock : PByteArray) : Longint;
{ IMPORTANT: verify block sizes before calling this routine }
var
biBlock : TLbBigInt;
InSize, OutSize : DWord;
begin
InSize := cRSACipherBlockSize[PrivateKey.KeySize];
OutSize := cRSAPlainBlockSize[PrivateKey.KeySize];
biBlock := TLbBigInt.Create(InSize);
try
biBlock.CopyBuffer(pInBlock^, InSize);
RSAEncryptBigInt(biBlock, PrivateKey, bt02, False);
if Integer(OutSize) < biBlock.Size then {!!.05}
raise Exception.Create('OutBlock size too small');
biBlock.ToBuffer(pOutBlock^, biBlock.Size);
finally
Result := biBlock.Size;
biBlock.Free;
end;
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA128(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock128;
var OutBlock : TRSACipherBlock128) : Longint;
{ encrypt plaintext block with 128-bit RSA public key }
begin
if (PublicKey.KeySize <> aks128) then
raise Exception.Create(sRSABlockSize128Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA128(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock128;
var OutBlock : TRSAPlainBlock128) : Longint;
{ decrypt ciphertext block with 128-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks128) then
raise Exception.Create(sRSABlockSize128Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA256(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock256;
var OutBlock : TRSACipherBlock256) : Longint;
{ encrypt plaintext block with 256-bit RSA public key }
begin
if (PublicKey.KeySize <> aks256) then
raise Exception.Create(sRSABlockSize256Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA256(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock256;
var OutBlock : TRSAPlainBlock256) : Longint;
{ decrypt ciphertext block with 256-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks256) then
raise Exception.Create(sRSABlockSize256Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA512(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock512;
var OutBlock : TRSACipherBlock512) : Longint;
{ encrypt plaintext block with 512-bit RSA public key }
begin
if (PublicKey.KeySize <> aks512) then
raise Exception.Create(sRSABlockSize512Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA512(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock512;
var OutBlock : TRSAPlainBlock512) : Longint;
{ decrypt ciphertext block with 512-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks512) then
raise Exception.Create(sRSABlockSize512Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA768(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock768;
var OutBlock : TRSACipherBlock768) : Longint;
{ encrypt plaintext block with 768-bit RSA public key }
begin
if (PublicKey.KeySize <> aks768) then
raise Exception.Create(sRSABlockSize768Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA768(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock768;
var OutBlock : TRSAPlainBlock768) : Longint;
{ decrypt ciphertext block with 768-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks768) then
raise Exception.Create(sRSABlockSize768Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA1024(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock1024;
var OutBlock : TRSACipherBlock1024) : Longint;
{ encrypt plaintext block with 1024-bit RSA public key }
begin
if (PublicKey.KeySize <> aks1024) then
raise Exception.Create(sRSABlockSize1024Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA1024(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock1024;
var OutBlock : TRSAPlainBlock1024) : Longint;
{ decrypt ciphertext block with 1024-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks1024) then
raise Exception.Create(sRSABlockSize1024Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA2048(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock2048;
var OutBlock : TRSACipherBlock2048) : Longint;
{ encrypt plaintext block with 2048-bit RSA public key }
begin
if (PublicKey.KeySize <> aks2048) then
raise Exception.Create(sRSABlockSize2048Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA2048(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock2048;
var OutBlock : TRSAPlainBlock2048) : Longint;
{ decrypt ciphertext block with 2048-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks2048) then
raise Exception.Create(sRSABlockSize2048Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function EncryptRSA3072(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock3072;
var OutBlock : TRSACipherBlock3072) : Longint;
{ encrypt plaintext block with 3072-bit RSA public key }
begin
if (PublicKey.KeySize <> aks3072) then
raise Exception.Create(sRSABlockSize3072Err);
Result := EncryptRSAEx(PublicKey, @InBlock, @OutBlock, SizeOf(InBlock));
end;
{ -------------------------------------------------------------------------- }
{!!.02}
function DecryptRSA3072(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock3072;
var OutBlock : TRSAPlainBlock3072) : Longint;
{ decrypt ciphertext block with 3072-bit RSA private key }
begin
if (PrivateKey.KeySize <> aks3072) then
raise Exception.Create(sRSABlockSize3072Err);
Result := DecryptRSAEx(PrivateKey, @InBlock, @OutBlock);
end;
{ -------------------------------------------------------------------------- }
function EncryptRSA(PublicKey : TLbRSAKey; const InBlock : TRSAPlainBlock;
var OutBlock : TRSACipherBlock) : Longint;
{ encrypt plaintext block with 512-bit RSA public key }
begin
Result := EncryptRSA512(PublicKey, InBlock, OutBlock); {!!.02}
end;
{ -------------------------------------------------------------------------- }
function DecryptRSA(PrivateKey : TLbRSAKey; const InBlock : TRSACipherBlock;
var OutBlock : TRSAPlainBlock) : Longint;
{ decrypt ciphertext block with 512-bit RSA private key }
begin
Result := DecryptRSA512(PrivateKey, InBlock, OutBlock); {!!.02}
end;
{ -------------------------------------------------------------------------- }
procedure RSAEncryptFile(const InFile, OutFile : string;
Key : TLbRSAKey; Encrypt : Boolean);
{ encrypt/decrypt file data with RSA key }
var
InStream, OutStream : TStream;
begin
InStream := TFileStream.Create(InFile, fmOpenRead or fmShareDenyWrite);
try
OutStream := TFileStream.Create(OutFile, fmCreate);
try
RSAEncryptStream(InStream, OutStream, Key, Encrypt);
finally
OutStream.Free;
end;
finally
InStream.Free;
end;
end;
{ -------------------------------------------------------------------------- }
procedure RSAEncryptStream(InStream, OutStream : TStream;
Key : TLbRSAKey; Encrypt : Boolean);
{ encrypt/decrypt stream data with RSA key }
var
InBlkCount : Integer;
InBlkSize, OutBlkSize : Integer;
PlainBlockSize, CipherBlockSize : Integer;
i : Integer;
pInBlk, pOutBlk : Pointer;
PlainBlock, CipherBlock : TRSACipherBlock3072;
begin
PlainBlockSize := cRSAPlainBlockSize[Key.KeySize];
CipherBlockSize := cRSACipherBlockSize[Key.KeySize];
if Encrypt then begin
pInBlk := @PlainBlock;
pOutBlk := @CipherBlock;
InBlkSize := PlainBlockSize;
OutBlkSize := CipherBlockSize;
end else begin
pInBlk := @CipherBlock;
pOutBlk := @PlainBlock;
InBlkSize := CipherBlockSize;
OutBlkSize := PlainBlockSize;
end;
InBlkCount := InStream.Size div InBlkSize;
if (InStream.Size mod InBlkSize) > 0 then
Inc(InBlkCount);
{ process all except the last block }
for i := 1 to (InBlkCount - 1) do begin
InStream.Read(pInBlk^, InBlkSize);
if Encrypt then
EncryptRSAEx(Key, pInBlk, pOutBlk, InBlkSize)
else
DecryptRSAEx(Key, pInBlk, pOutBlk);
OutStream.Write(pOutBlk^, OutBlkSize);
end;
{ process the last block }
i := InStream.Read(pInBlk^, InBlkSize);
if Encrypt then
i := EncryptRSAEx(Key, pInBlk, pOutBlk, i)
else
i := DecryptRSAEx(Key, pInBlk, pOutBlk);
OutStream.Write(pOutBlk^, i);
end;
{ -------------------------------------------------------------------------- }
function RSAEncryptString(const InString : RawByteString; Key : TLbRSAKey; Encrypt : Boolean) : RawByteString;
{ encrypt/decrypt string data with RSA key }
var
InStream : TMemoryStream;
OutStream : TMemoryStream;
WorkStream : TMemoryStream;
begin
InStream := TMemoryStream.Create;
OutStream := TMemoryStream.Create;
WorkStream := TMemoryStream.Create;
InStream.Write(InString[1], Length(InString));
InStream.Position := 0;
if Encrypt then begin
RSAEncryptStream(InStream, WorkStream, Key, True);
WorkStream.Position := 0;
LbEncodeBase64(WorkStream, OutStream);
end else begin
LbDecodeBase64(InStream, WorkStream);
WorkStream.Position := 0;
RSAEncryptStream(WorkStream, OutStream, Key, False);
end;
OutStream.Position := 0;
SetLength(Result, OutStream.Size);
OutStream.Read(Result[1], OutStream.Size);
InStream.Free;
OutStream.Free;
WorkStream.Free;
end;
{ == TLbRSAKey ============================================================= }
constructor TLbRSAKey.Create(aKeySize : TLbAsymKeySize);
{ initialization }
begin
inherited Create(aKeySize);
FModulus := TLbBigInt.Create(cLbAsymKeyBytes[FKeySize]);
FExponent := TLbBigInt.Create(cLbAsymKeyBytes[FKeySize]);
end;
{ -------------------------------------------------------------------------- }
destructor TLbRSAKey.Destroy;
{ finalization }
begin
FModulus.Free;
FExponent.Free;
inherited Destroy;
end;
{ -------------------------------------------------------------------------- }
procedure TLbRSAKey.Assign(aKey : TLbAsymmetricKey);
{ copy exponent and modulus values from another key }
begin
inherited Assign(aKey);
if (aKey is TLbRSAKey) then begin
FModulus.Copy(TLbRSAKey(aKey).Modulus);
FExponent.Copy(TLbRSAKey(aKey).Exponent);
end;
end;
{ -------------------------------------------------------------------------- }
procedure TLbRSAKey.Clear;
{ reset exponent and modulus }
begin
FModulus.Clear;
FExponent.Clear;
end;
{ -------------------------------------------------------------------------- }
function TLbRSAKey.GetModulusAsHexString : string;
{ return "big to little" hex string representation of modulus }
begin
Result := FModulus.IntStr;
end;
{ -------------------------------------------------------------------------- }
procedure TLbRSAKey.SetModulusAsHexString(Value : string);
{ set modulus to value represented by "big to little" hex string }
begin
FModulus.IntStr := Value;
end;
{ -------------------------------------------------------------------------- }
function TLbRSAKey.GetExponentAsHexString : string;
{ return "big to little" hex string representation of exponent }
begin
Result := FExponent.IntStr;
end;
{ -------------------------------------------------------------------------- }
procedure TLbRSAKey.SetExponentAsHexString(Value : string);
{ set exponent to value represented by "big to little" hex string }
begin
FExponent.IntStr := Value;
end;
{------------------------------------------------------------------------------}
function TLbRSAKey.CreateASNKey(Input : pByteArray; Length : Integer) : Integer;
const
TAG30 = $30;
var
ExpSize : Integer;
ModSize : Integer;
Total : Integer;
pInput : PByteArray;
Max : Integer;
begin
pInput := Input;
Max := Length;
ModSize := EncodeASN1(FModulus, pInput, Max);
ExpSize := EncodeASN1(FExponent, pInput, Max);
Total := ExpSize + ModSize;
CreateASN1(Input^, Total, TAG30);
Result := Total;
end;
{------------------------------------------------------------------------------}
function TLbRSAKey.ParseASNKey(Input : PByte; Length : Integer) : Boolean;
var
Tag : Integer;
Max : Integer;
pInput : PByte;
begin
Max := Length;
pInput := Input;
{ check for sequence }
Tag := GetASN1StructNum(pInput, Max);
GetASN1StructLen(pInput, Max);
if (Tag <> ASN1_TYPE_SEQUENCE) then
raise Exception.Create(sRSAKeyBadKey);
KeySize := KeySizeFromBytes(ParseASN1(pInput, Max, FModulus));
ParseASN1(pInput, Max, FExponent);
Result := (Max = 0);
end;
{ == TLbRSA ================================================================ }
function TLbRSA.CalculatePQ: Boolean;
var
d, e, n : TLbBigInt;
k, r, t, y, g, Nminus1, j, TWO, x : TLbBigInt;
index : Integer;
IsFound, IsDone : boolean;
begin
IsFound := false;
d := FPrivateKey.Exponent;
e := FPublicKey.Exponent;
n := FPrivateKey.Modulus;
k := TLbBigInt.Create(d.Size);
try
k.Copy(d);
k.Multiply(e);
k.SubtractByte($01);
if k.IsEven then
begin
r := nil;
t := nil;
y := nil;
g := nil;
Nminus1 := nil; //n - 1
TWO := nil;
try
Nminus1 := TLbBigInt.Create(n.Size);
Nminus1.Copy(n);
Nminus1.SubtractByte($01);
TWO := TLbBigInt.Create(d.Size);
TWO.CopyByte($02);
r := TLbBigInt.Create(k.Size);
r.Copy(k);
r.Divide(TWO);
t := TLbBigInt.Create(k.Size);
t.CopyByte($01);
while r.IsEven do
begin
r.Divide(TWO);
t.AddByte($01);
end;
y := TLbBigInt.Create(n.Size);
g := TLbBigInt.Create(n.Size);
index := 0;
while (index < 100) and not IsFound do
begin
g.RandomBytes(n.Size);
y.Copy(g);
y.PowerAndMod(r, n);
if (not y.IsOne and (y.Compare(Nminus1) <> 0)) then
begin
j := nil;
x := nil;
try
x := TLbBigInt.Create(y.Size);
j := TLbBigInt.Create(k.Size);
j.CopyByte($01);
IsDone := false;
while (j.Compare(t) <= 0) and not IsDone do
begin
x.Copy(y);
x.PowerAndMod(TWO, n);
IsFound := x.IsOne;
IsDone := IsFound or (x.Compare(Nminus1) = 0);
if not IsDone then
begin
y.Copy(x);
end;
j.AddByte($01);
end;
if not IsFound then
begin
x.Copy(y);
x.PowerAndMod(TWO, n);
IsFound := x.IsOne;
end;
finally
j.Free;
x.Free;