-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathmormot.crypt.rsa.pas
3535 lines (3316 loc) · 112 KB
/
mormot.crypt.rsa.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
/// Framework Core RSA Support
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.crypt.rsa;
{
*****************************************************************************
Rivest-Shamir-Adleman (RSA) Public-Key Cryptography
- RSA Oriented Big-Integer Computation
- RSA Low-Level Cryptography Functions
- Registration of our RSA Engine to the TCryptAsym Factory
*****************************************************************************
Legal Notice: as stated by our LICENSE.md terms, make sure that you comply
to any restriction about the use of cryptographic software in your country.
}
interface
{$I ..\mormot.defines.inc}
uses
classes,
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.rtti,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.crypt.core,
mormot.crypt.secure;
{
Implementation notes:
- new pure pascal OOP design of BigInt computation optimized for RSA process
- garbage collection of BigInt instances, with proper anti-forensic wiping
- use half-registers (HalfUInt) for efficient computation on all CPUs
- dedicated x86_64/i386 asm for core computation routines (noticeable speedup)
- slower than OpenSSL, but likely the fastest FPC or Delphi native RSA library
- includes FIPS-level RSA keypair validation and generation
- features both RSASSA-PKCS1-v1_5 and RSASSA-PSS signature schemes
- started as a fcl-hash fork, but full rewrite inspired by Mbed TLS source
- references: https://github.com/Mbed-TLS/mbedtls and the Handbook of Applied
Cryptography (HAC) at https://cacr.uwaterloo.ca/hac/about/chap4.pdf
- will register as Asym 'RS256','RS384','RS512' algorithms (if not overriden
by mormot.crypt.openssl), keeping 'RS256-int' and 'PS256-int' for this unit
- used by mormot.crypt.x509 to handle RSA signatures of its X.509 Certificates
}
{.$define USEBARRET}
// could be defined to enable Barret reduction (slower and with wrong results)
{ **************** RSA Oriented Big-Integer Computation }
type
/// exception class raised by this unit
ERsaException = class(ESynException);
const
/// number of bytes in a HalfUInt, i.e. 2 on CPU32 and 4 on CPU64
HALF_BYTES = SizeOf(HalfUInt);
/// number of bits in a HalfUInt, i.e. 16 on CPU32 and 32 on CPU64
HALF_BITS = HALF_BYTES * 8;
/// number of power of two bits in a HalfUInt, i.e. 4 on CPU32 and 5 on CPU64
HALF_SHR = {$ifdef CPU32} 4 {$else} 5 {$endif};
/// maximum HalfUInt value + 1
RSA_RADIX = PtrUInt({$ifdef CPU32} $10000 {$else} $100000000 {$endif});
/// maximum PtrUInt value - 1
RSA_MAX = PtrUInt(-1);
type
PBigInt = ^TBigInt;
PPBigInt = ^PBigInt;
TRsaContext = class;
/// refine the extend of TBigInt.MatchKnownPrime() detection
// - bspFast will search for known primes < 256 - e.g. 2048-bit at 250K/s
// - bspMost will search for known primes < 2000 - e.g. 2048-bit at 45K/s and
// is in practice sufficient to detect most primes (Mbed TLS check < 1000)
// - bspAll will search for known primes < 18000 - e.g. 2048-bit at 6.5K/s
// - see RSA_DEFAULT_GENERATION_KNOWNPRIME = bspMost constant below
TBigIntSimplePrime = (
bspFast,
bspMost,
bspAll);
/// define how TBigInt.Divide computes its result
TBigIntDivide = (
bidDivide,
bidMod,
bidModNorm);
/// store one Big Integer value with proper COW support
// - each value is owned as PBigInt by an associated TRsaContext instance
// - you should call TBigInt.Release() once done with any instance
{$ifdef USERECORDWITHMETHODS}
TBigInt = record
{$else}
TBigInt = object
{$endif USERECORDWITHMETHODS}
private
fNextFree: PBigInt; // next bigint in the Owner free instance cache
function UsedBytes: integer;
procedure Resize(n: integer; nozero: boolean = false);
{$ifdef USEBARRET}
function TruncateMod(modulus: integer): PBigInt;
{$ifdef HASINLINE} inline; {$endif}
/// partial multiplication between two Big Integer values
// - will eventually release both self and b instances
function MultiplyPartial(b: PBigInt; InnerPartial: PtrInt;
OuterPartial: PtrInt): PBigInt;
{$endif USEBARRET}
public
/// the associated Big Integer RSA context
// - used to store modulo constants, and maintain an internal instance cache
Owner: TRsaContext;
/// number of HalfUInt in this Big Integer value
Size: integer;
/// number of HalfUInt allocated for this Big Integer value
Capacity: integer;
/// internal reference counter
// - equals -1 for permanent/constant storage
RefCnt: integer;
/// raw access to the actual HalfUInt data
Value: PHalfUIntArray;
/// comparison with another Big Integer value
// - values should have been Trim-med for the size to match
function Compare(b: PBigInt; andrelease: boolean = false): integer; overload;
/// comparison with another Unsigned Integer value
// - values should have been Trim-med for the size to match
function Compare(u: HalfUInt; andrelease: boolean = false): integer; overload;
/// make a COW instance, increasing RefCnt and returning self
function Copy: PBigInt;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// allocate a new Big Integer value with the same data as an existing one
function Clone: PBigInt;
/// mark the value with a RefCnt < 0
function SetPermanent: PBigInt;
/// mark the value with a RefCnt = 1
function ResetPermanent: PBigInt;
/// decreases the value RefCnt, saving it in the internal FreeList once done
procedure Release;
/// a wrapper to ResetPermanent then Release
// - before release, fill the buffer with zeros to avoid forensic leaking
procedure ResetPermanentAndRelease;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// export a Big Integer value into a binary buffer
procedure Save(data: PByteArray; bytes: integer; andrelease: boolean); overload;
/// export a Big Integer value into a binary RawByteString
function Save(andrelease: boolean = false): RawByteString; overload;
/// delete any meaningless leading zeros and return self
function Trim: PBigInt;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// quickly check if contains 0
function IsZero: boolean;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// quickly check if contains an even number, i.e. last bit is 0
function IsEven: boolean;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// quickly check if contains an odd number, i.e. last bit is 1
function IsOdd: boolean;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// check if a given bit is set to 1
function BitIsSet(bit: PtrUInt): boolean;
{$ifdef HASINLINE} inline; {$endif}
/// search the position of the first bit set
function BitCount: integer;
/// return the number of bits set in this value
function BitSetCount: integer;
/// return the index of the highest bit set
function FindMaxBit: integer;
/// return the index of the lowest bit set
function FindMinBit: integer;
/// shift right the internal data by some bits = div per 2/4/8...
function ShrBits(bits: integer = 1): PBigInt;
/// shift left the internal data by some bits = mul per 2/4/8...
function ShlBits(bits: integer = 1): PBigInt;
/// shift right the internal data HalfUInt by a number of slots
function RightShift(n: integer): PBigInt;
/// shift left the internal data HalfUInt by a number of slots
function LeftShift(n: integer): PBigInt;
/// compute the GCD of two numbers using Euclidean algorithm
function GreatestCommonDivisor(b: PBigInt): PBigInt;
/// compute the sum of two Big Integer values
// - returns self := self + b as result
// - will eventually release the b instance
function Add(b: PBigInt): PBigInt;
/// compute the difference of two Big Integer values
// - returns self := abs(self - b) as result, and NegativeResult^ as its sign
// - will eventually release the b instance
function Substract(b: PBigInt; NegativeResult: PBoolean = nil): PBigInt;
/// division or modulo computation
// - self is the numerator
// - if Compute is bidDivide, v is the denominator; otherwise, is the modulus
// - will eventually release the v instance
function Divide(v: PBigInt; Compute: TBigIntDivide = bidDivide;
Remainder: PPBigInt = nil): PBigInt;
/// modulo computation
// - just redirect to Divide(v.Copy, bidMod)
// - won't eventually release the v instance thanks to v.Copy
function Modulo(v: PBigInt): PBigInt;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// standard multiplication between two Big Integer values
// - will eventually release both self and b instances
function Multiply(b: PBigInt): PBigInt;
/// standard multiplication by itself
// - will allocate a new Big Integer value and release self
function Square: PBigint;
{$ifdef HASINLINE} inline; {$endif}
/// add an unsigned integer value
function IntAdd(b: HalfUInt): PBigInt;
/// substract an unsigned integer value
function IntSub(b: HalfUInt): PBigInt;
/// multiply by an unsigned integer value
// - returns self := self * b
// - will eventually release the self instance
function IntMultiply(b: HalfUInt): PBigInt;
/// divide by an unsigned integer value
// - returns self := self div b
// - optionally return self mod b
function IntDivide(b: HalfUInt; optmod: PHalfUInt = nil): PBigInt;
/// compute the modulo by an unsigned integer value
// - returns self mod b, keeping self untouched
function IntMod(b: HalfUInt): PtrUInt;
/// division and modulo by 10 computation
// - computes self := self div 10 and return self mod 10
function IntDivMod10: PtrUInt;
/// compute the modular inverse, i.e. self^-1 mod m
// - will eventually release the m instance
function ModInverse(m: PBigInt): PBigInt;
/// check if this value is divisable by a small prime
// - detection coverage can be customized from default primes < 2000
function MatchKnownPrime(Extend: TBigIntSimplePrime): boolean;
/// check if the number is (likely to be) a prime following HAC 4.44
// - can set a known simple primes Extend and Miller-Rabin tests Iterations
function IsPrime(Extend: TBigIntSimplePrime = bspMost;
Iterations: integer = 10): boolean;
/// guess a random prime number of the exact current size
// - loop over TAesPrng.Fill and IsPrime method within a timeout period
// - if Iterations is too low, FIPS 4.48 recommendation will be forced
function FillPrime(Extend: TBigIntSimplePrime; Iterations: integer;
EndTix: Int64): boolean;
/// return the crc32c hash of this Big Integer value binary
function ToHash: cardinal;
/// return the Big Integer value as hexadecimal
function ToHexa: RawUtf8;
/// return the Big Integer value as text with base-10 digits
// - self will remain untouched unless noclone is set
function ToText(noclone: boolean = false): RawUtf8;
/// could be used for low-level console debugging of a raw value
procedure Debug(const name: shortstring; full: boolean = false);
end;
/// define Normal, P and Q pre-computed modulos
TRsaModulo = (
rmM,
rmP,
rmQ);
/// store Normal, P and Q pre-computed modulos as PBigInt
TRsaModulos = array[TRsaModulo] of PBigInt;
/// how TRsaContext.Allocate should create the new allocated block
// - memory block is filled with 0 as by default raZeroed is defined
// - by default, a capacity overhead is allowed to the returned memory buffer,
// to avoid heap reallocation during computation - you can set raExactSize if
// you know the buffer size won't change (e.g. from TRsaContext.LoadPermanent)
TRsaAllocate = set of (
raZeroed,
raExactSize);
/// store one Big Integer computation context for RSA
// - will maintain its own set of reference-counted Big Integer values,
// for fast thread-local reuse and automated safe anti-forensic wipe
TRsaContext = class(TSynPersistent)
private
/// list of released PBigInt instance, ready to be re-used by Allocate()
fFreeList: PBigInt;
/// contains Modulus
fMod: TRsaModulos;
/// contains the normalized storage
fNormMod: TRsaModulos;
{$ifdef USEBARRET}
/// contains mu
fMu: TRsaModulos;
/// contains b(k+1)
fBk1: TRsaModulos;
{$endif USEBARRET}
public
/// the size of the sliding window
Window: integer;
/// number of active PBigInt
ActiveCount: integer;
/// number of PBigInt instances stored in the internal instances cache
FreeCount: integer;
/// as set by SetModulo() and used by Reduce() and ModPower()
CurrentModulo: TRsaModulo;
/// finalize this Big Integer context memory
destructor Destroy; override;
/// allocate a new zeroed Big Integer value of the specified precision
// - n is the number of TBitInt.Value[] items to initialize
function Allocate(n: integer; opt: TRsaAllocate = [raZeroed]): PBigint;
/// allocate a new Big Integer value from a 16/32-bit unsigned integer
function AllocateFrom(v: HalfUInt): PBigInt;
/// allocate a new Big Integer value from a ToHexa dump
function AllocateFromHex(const hex: RawUtf8): PBigInt;
/// call b^^.Release and set b^ := nil
procedure Release(const b: array of PPBigInt);
/// fill all released values with zero as anti-forensic safety measure
procedure WipeReleased;
/// allocate and import a Big Integer value from a big-endian binary buffer
function Load(data: PByteArray; bytes: integer;
opt: TRsaAllocate = []): PBigInt; overload;
/// allocate and import a Big Integer value from a big-endian binary buffer
function LoadPermanent(const data: RawByteString): PBigInt; overload;
/// pre-compute some of the internal constant slots for a given modulo
procedure SetModulo(b: PBigInt; modulo: TRsaModulo);
/// release the internal constant slots for a given modulo
procedure ResetModulo(modulo: TRsaModulo);
/// compute the reduction of a Big Integer value in a given modulo
// - if m is nil, SetModulo() should have previously be called
// - redirect to Divide() or use the Barret algorithm
// - will eventually release the b instance
function Reduce(b, m: PBigint): PBigInt;
/// compute a modular exponentiation, i.e. b^exp mod m
// - if m is nil, SetModulo() should have previously be called
// - will eventually release the b and exp instances
function ModPower(b, exp, m: PBigInt): PBigInt;
end;
const
/// generates RSA keypairs checking all known primes < 2000
// - bspMost seems the best compromise between performance and safety, since
// even Mbed TLS only try for primes < 1000
// - in practice bspFast is only slightly faster, and bspAll seems overkill
// - when profiling, the Miller-Rabin test takes 150 more time than bspMost
RSA_DEFAULT_GENERATION_KNOWNPRIME = bspMost;
/// generates RSA keypairs using a proven 2^-112 error probability from
// Miller-Rabin iterations
// - TBigInt.FillPrime will ensure FIPS 186-5 minimum iteration is always used
RSA_DEFAULT_GENERATION_ITERATIONS = 0;
/// generates RSA keypairs in a time-coherent fashion
{$ifdef CPUARM}
// - we have seen some weak Raspberry PI timeout so 30 seconds seems fair
RSA_DEFAULT_GENERATION_TIMEOUTMS = 30000;
{$else}
// - allow 10 seconds: typical time is around (or less) 1 second on Intel/AMD
RSA_DEFAULT_GENERATION_TIMEOUTMS = 10000;
{$endif CPUARM}
/// 2KB table of iterative differences of all known prime numbers < 18,000
// - as used by TBigInt.MatchKnownPrime
// - published in interface section for TTestCoreCrypto._RSA validation
BIGINT_PRIMES_DELTA: array[0 .. 258 * 8 - 1] of byte = (
2, 1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6,
8, 4, 2, 4, 2, 4,14, 4, 6, 2,10, 2, 6, 6, 4, 6, 6, 2,10, 2, 4, 2,12,12,
4, 2, 4, 6, 2,10, 6, 6, 6, 2, 6, 4, 2,10,14, 4, 2, 4,14, 6,10, 2, 4, 6,
8, 6, 6, 4, 6, 8, 4, 8,10, 2,10, 2, 6, 4, 6, 8, 4, 2, 4,12, 8, 4, 8, 4,
6,12, 2,18, 6,10, 6, 6, 2, 6,10, 6, 6, 2, 6, 6, 4, 2,12,10, 2, 4, 6, 6,
2,12, 4, 6, 8,10, 8,10, 8, 6, 6, 4, 8, 6, 4, 8, 4,14,10,12, 2,10, 2, 4,
2,10,14, 4, 2, 4,14, 4, 2, 4,20, 4, 8,10, 8, 4, 6, 6,14, 4, 6, 6, 8, 6,
12, 4, 6, 2,10, 2, 6,10, 2,10, 2, 6,18, 4, 2, 4, 6, 6, 8, 6, 6,22, 2,10,
8,10, 6, 6, 8,12, 4, 6, 6, 2, 6,12,10,18, 2, 4, 6, 2, 6, 4, 2, 4,12, 2,
6,34, 6, 6, 8,18,10,14, 4, 2, 4, 6, 8, 4, 2, 6,12,10, 2, 4, 2, 4, 6,12,
12, 8,12, 6, 4, 6, 8, 4, 8, 4,14, 4, 6, 2, 4, 6, 2, 6,10,20, 6, 4, 2,24,
4, 2,10,12, 2,10, 8, 6, 6, 6,18, 6, 4, 2,12,10,12, 8,16,14, 6, 4, 2, 4,
2,10,12, 6, 6,18, 2,16, 2,22, 6, 8, 6, 4, 2, 4, 8, 6,10, 2,10,14,10, 6,
12, 2, 4, 2,10,12, 2,16, 2, 6, 4, 2,10, 8,18,24, 4, 6, 8,16, 2, 4, 8,16,
2, 4, 8, 6, 6, 4,12, 2,22, 6, 2, 6, 4, 6,14, 6, 4, 2, 6, 4, 6,12, 6, 6,
14, 4, 6,12, 8, 6, 4,26,18,10, 8, 4, 6, 2, 6,22,12, 2,16, 8, 4,12,14,10,
2, 4, 8, 6, 6, 4, 2, 4, 6, 8, 4, 2, 6,10, 2,10, 8, 4,14,10,12, 2, 6, 4,
2,16,14, 4, 6, 8, 6, 4,18, 8,10, 6, 6, 8,10,12,14, 4, 6, 6, 2,28, 2,10,
8, 4,14, 4, 8,12, 6,12, 4, 6,20,10, 2,16,26, 4, 2,12, 6, 4,12, 6, 8, 4,
8,22, 2, 4, 2,12,28, 2, 6, 6, 6, 4, 6, 2,12, 4,12, 2,10, 2,16, 2,16, 6,
20,16, 8, 4, 2, 4, 2,22, 8,12, 6,10, 2, 4, 6, 2, 6,10, 2,12,10, 2,10,14,
6, 4, 6, 8, 6, 6,16,12, 2, 4,14, 6, 4, 8,10, 8, 6, 6,22, 6, 2,10,14, 4,
6,18, 2,10,14, 4, 2,10,14, 4, 8,18, 4, 6, 2, 4, 6, 2,12, 4,20,22,12, 2,
4, 6, 6, 2, 6,22, 2, 6,16, 6,12, 2, 6,12,16, 2, 4, 6,14, 4, 2,18,24,10,
6, 2,10, 2,10, 2,10, 6, 2,10, 2,10, 6, 8,30,10, 2,10, 8, 6,10,18, 6,12,
12, 2,18, 6, 4, 6, 6,18, 2,10,14, 6, 4, 2, 4,24, 2,12, 6,16, 8, 6, 6,18,
16, 2, 4, 6, 2, 6, 6,10, 6,12,12,18, 2, 6, 4,18, 8,24, 4, 2, 4, 6, 2,12,
4,14,30,10, 6,12,14, 6,10,12, 2, 4, 6, 8, 6,10, 2, 4,14, 6, 6, 4, 6, 2,
10, 2,16,12, 8,18, 4, 6,12, 2, 6, 6, 6,28, 6,14, 4, 8,10, 8,12,18, 4, 2,
4,24,12, 6, 2,16, 6, 6,14,10,14, 4,30, 6, 6, 6, 8, 6, 4, 2,12, 6, 4, 2,
6,22, 6, 2, 4,18, 2, 4,12, 2, 6, 4,26, 6, 6, 4, 8,10,32,16, 2, 6, 4, 2,
4, 2,10,14, 6, 4, 8,10, 6,20, 4, 2, 6,30, 4, 8,10, 6, 6, 8, 6,12, 4, 6,
2, 6, 4, 6, 2,10, 2,16, 6,20, 4,12,14,28, 6,20, 4,18, 8, 6, 4, 6,14, 6,
6,10, 2,10,12, 8,10, 2,10, 8,12,10,24, 2, 4, 8, 6, 4, 8,18,10, 6, 6, 2,
6,10,12, 2,10, 6, 6, 6, 8, 6,10, 6, 2, 6, 6, 6,10, 8,24, 6,22, 2,18, 4,
8,10,30, 8,18, 4, 2,10, 6, 2, 6, 4,18, 8,12,18,16, 6, 2,12, 6,10, 2,10,
2, 6,10,14, 4,24, 2,16, 2,10, 2,10,20, 4, 2, 4, 8,16, 6, 6, 2,12,16, 8,
4, 6,30, 2,10, 2, 6, 4, 6, 6, 8, 6, 4,12, 6, 8,12, 4,14,12,10,24, 6,12,
6, 2,22, 8,18,10, 6,14, 4, 2, 6,10, 8, 6, 4, 6,30,14,10, 2,12,10, 2,16,
2,18,24,18, 6,16,18, 6, 2,18, 4, 6, 2,10, 8,10, 6, 6, 8, 4, 6, 2,10, 2,
12, 4, 6, 6, 2,12, 4,14,18, 4, 6,20, 4, 8, 6, 4, 8, 4,14, 6, 4,14,12, 4,
2,30, 4,24, 6, 6,12,12,14, 6, 4, 2, 4,18, 6,12, 8, 6, 4,12, 2,12,30,16,
2, 6,22,14, 6,10,12, 6, 2, 4, 8,10, 6, 6,24,14, 6, 4, 8,12,18,10, 2,10,
2, 4, 6,20, 6, 4,14, 4, 2, 4,14, 6,12,24,10, 6, 8,10, 2,30, 4, 6, 2,12,
4,14, 6,34,12, 8, 6,10, 2, 4,20,10, 8,16, 2,10,14, 4, 2,12, 6,16, 6, 8,
4, 8, 4, 6, 8, 6, 6,12, 6, 4, 6, 6, 8,18, 4,20, 4,12, 2,10, 6, 2,10,12,
2, 4,20, 6,30, 6, 4, 8,10,12, 6, 2,28, 2, 6, 4, 2,16,12, 2, 6,10, 8,24,
12, 6,18, 6, 4,14, 6, 4,12, 8, 6,12, 4, 6,12, 6,12, 2,16,20, 4, 2,10,18,
8, 4,14, 4, 2, 6,22, 6,14, 6, 6,10, 6, 2,10, 2, 4, 2,22, 2, 4, 6, 6,12,
6,14,10,12, 6, 8, 4,36,14,12, 6, 4, 6, 2,12, 6,12,16, 2,10, 8,22, 2,12,
6, 4, 6,18, 2,12, 6, 4,12, 8, 6,12, 4, 6,12, 6, 2,12,12, 4,14, 6,16, 6,
2,10, 8,18, 6,34, 2,28, 2,22, 6, 2,10,12, 2, 6, 4, 8,22, 6, 2,10, 8, 4,
6, 8, 4,12,18,12,20, 4, 6, 6, 8, 4, 2,16,12, 2,10, 8,10, 2, 4, 6,14,12,
22, 8,28, 2, 4,20, 4, 2, 4,14,10,12, 2,12,16, 2,28, 8,22, 8, 4, 6, 6,14,
4, 8,12, 6, 6, 4,20, 4,18, 2,12, 6, 4, 6,14,18,10, 8,10,32, 6,10, 6, 6,
2, 6,16, 6, 2,12, 6,28, 2,10, 8,16, 6, 8, 6,10,24,20,10, 2,10, 2,12, 4,
6,20, 4, 2,12,18,10, 2,10, 2, 4,20,16,26, 4, 8, 6, 4,12, 6, 8,12,12, 6,
4, 8,22, 2,16,14,10, 6,12,12,14, 6, 4,20, 4,12, 6, 2, 6, 6,16, 8,22, 2,
28, 8, 6, 4,20, 4,12,24,20, 4, 8,10, 2,16, 2,12,12,34, 2, 4, 6,12, 6, 6,
8, 6, 4, 2, 6,24, 4,20,10, 6, 6,14, 4, 6, 6, 2,12, 6,10, 2,10, 6,20, 4,
26, 4, 2, 6,22, 2,24, 4, 6, 2, 4, 6,24, 6, 8, 4, 2,34, 6, 8,16,12, 2,10,
2,10, 6, 8, 4, 8,12,22, 6,14, 4,26, 4, 2,12,10, 8, 4, 8,12, 4,14, 6,16,
6, 8, 4, 6, 6, 8, 6,10,12, 2, 6, 6,16, 8, 6, 6,12,10, 2, 6,18, 4, 6, 6,
6,12,18, 8, 6,10, 8,18, 4,14, 6,18,10, 8,10,12, 2, 6,12,12,36, 4, 6, 8,
4, 6, 2, 4,18,12, 6, 8, 6, 6, 4,18, 2, 4, 2,24, 4, 6, 6,14,30, 6, 4, 6,
12, 6,20, 4, 8, 4, 8, 6, 6, 4,30, 2,10,12, 8,10, 8,24, 6,12, 4,14, 4, 6,
2,28,14,16, 2,12, 6, 4,20,10, 6, 6, 6, 8,10,12,14,10,14,16,14,10,14, 6,
16, 6, 8, 6,16,20,10, 2, 6, 4, 2, 4,12, 2,10, 2, 6,22, 6, 2, 4,18, 8,10,
8,22, 2,10,18,14, 4, 2, 4,18, 2, 4, 6, 8,10, 2,30, 4,30, 2,10, 2,18, 4,
18, 6,14,10, 2, 4,20,36, 6, 4, 6,14, 4,20,10,14,22, 6, 2,30,12,10,18, 2,
4,14, 6,22,18, 2,12, 6, 4, 8, 4, 8, 6,10, 2,12,18,10,14,16,14, 4, 6, 6,
2, 6, 4, 2,28, 2,28, 6, 2, 4, 6,14, 4,12,14,16,14, 4, 6, 8, 6, 4, 6, 6,
6, 8, 4, 8, 4,14,16, 8, 6, 4,12, 8,16, 2,10, 8, 4, 6,26, 6,10, 8, 4, 6,
12,14,30, 4,14,22, 8,12, 4, 6, 8,10, 6,14,10, 6, 2,10,12,12,14, 6, 6,18,
10, 6, 8,18, 4, 6, 2, 6,10, 2,10, 8, 6, 6,10, 2,18,10, 2,12, 4, 6, 8,10,
12,14,12, 4, 8,10, 6, 6,20, 4,14,16,14,10, 8,10,12, 2,18, 6,12,10,12, 2,
4, 2,12, 6, 4, 8, 4,44, 4, 2, 4, 2,10,12, 6, 6,14, 4, 6, 6, 6, 8, 6,36,
18, 4, 6, 2,12, 6, 6, 6, 4,14,22,12, 2,18,10, 6,26,24, 4, 2, 4, 2, 4,14,
4, 6, 6, 8,16,12, 2,42, 4, 2, 4,24, 6, 6, 2,18, 4,14, 6,28,18,14, 6,10,
12, 2, 6,12,30, 6, 4, 6, 6,14, 4, 2,24, 4, 6, 6,26,10,18, 6, 8, 6, 6,30,
4,12,12, 2,16, 2, 6, 4,12,18, 2, 6, 4,26,12, 6,12, 4,24,24,12, 6, 2,12,
28, 8, 4, 6,12, 2,18, 6, 4, 6, 6,20,16, 2, 6, 6,18,10, 6, 2, 4, 8, 6, 6,
24,16, 6, 8,10, 6,14,22, 8,16, 6, 2,12, 4, 2,22, 8,18,34, 2, 6,18, 4, 6,
6, 8,10, 8,18, 6, 4, 2, 4, 8,16, 2,12,12, 6,18, 4, 6, 6, 6, 2, 6,12,10,
20,12,18, 4, 6, 2,16, 2,10,14, 4,30, 2,10,12, 2,24, 6,16, 8,10, 2,12,22,
6, 2,16,20,10, 2,12,12,18,10,12, 6, 2,10, 2, 6,10,18, 2,12, 6, 4, 6, 2);
/// compute the base-10 decimal text from a Big Integer binary buffer
// - wrap PBigInt.ToText from LoadPermanent(der) in a temporary TRsaContext
function BigIntToText(const der: TCertDer): RawUtf8;
/// branchless comparison of two Big Integer internal buffer values
function CompareBI(A, B: HalfUInt): integer;
{$ifdef HASINLINE} inline; {$endif}
{ **************** RSA Low-Level Cryptography Functions }
type
/// the TRsa.Generate method result
TRsaGenerateResult = (
rgrSuccess,
rgrIncorrectParams,
rgrTimeout,
rgrRandomGeneratorFailure,
rgrWeakBitsMayRetry);
/// store a RSA public key
// - with DER (therefore PEM) serialization support
// - e.g. as decoded from an X509 certificate
{$ifdef USERECORDWITHMETHODS}
TRsaPublicKey = record
{$else}
TRsaPublicKey = object
{$endif USERECORDWITHMETHODS}
public
/// RSA key Modulus m or n
Modulus: RawByteString;
/// RSA key Public exponent e (typically 65537)
Exponent: RawByteString;
/// serialize this public key as binary PKCS#1 DER format
function ToDer: TCertDer;
/// serialize this public key as ASN1_SEQ, as stored in a X509 certificate
function ToSubjectPublicKey: RawByteString;
/// unserialize a public key from binary PKCS#1 DER format
// - will try and fallback to a ASN1_SEQ, as stored in a X509 certificate
function FromDer(const der: TCertDer): boolean;
end;
/// store a RSA private key
// - with DER (therefore PEM) serialization support
// - we don't support any PKCS encryption yet - ensure the private key
// PEM file is safely stored with proper user access restrictions
{$ifdef USERECORDWITHMETHODS}
TRsaPrivateKey = record
{$else}
TRsaPrivateKey = object
{$endif USERECORDWITHMETHODS}
public
/// field layout is typically 0
Version: integer;
/// RSA key m or n
Modulus: RawByteString;
/// RSA key Public exponent e (typically 65537)
PublicExponent: RawByteString;
/// RSA key Private exponent d
PrivateExponent: RawByteString;
/// RSA key prime factor p of n
Prime1: RawByteString;
/// RSA key prime factor q of n
Prime2: RawByteString;
/// RSA key d mod (p - 1)
Exponent1: RawByteString;
/// RSA key d mod (q - 1)
Exponent2: RawByteString;
/// RSA key CRT coefficient q^(-1) mod p
Coefficient: RawByteString;
/// serialize this private key as binary DER format
// - note that the layout follows PKCS#8 "openssl genrsa -out priv.pem 2048"
// layout, but not "A.1.2. RSA Private Key Syntax" PKCS#1 as of RFC 8017
function ToDer: TCertDer;
/// unserialize a private key from binary DER format
// - will recognize both PCKS#8 "openssl genrsa -out priv.pem 2048" ASN.1
// layout and "A.1.2. RSA Private Key Syntax" PKCS#1 as of RFC 8017
function FromDer(const der: TCertDer): boolean;
/// check if this private key match a given public key
function Match(const Pub: TRsaPublicKey): boolean;
/// you should better call this function to avoid forensic leaks
procedure Done;
end;
/// main RSA processing class for both public or private key
// - supports PEM/DER persistence, and can Generate a new key pair
// - holds all its PBigInt values in its parent TRsaContext
// - uses regular RSASSA-PKCS1-v1_5 encoding - see TRsaPss for RSASSA-PSS
// - note that only Verify() and Sign() methods are thread-safe
// - this implementation follows RFC 8017 specifications
TRsa = class(TRsaContext)
protected
fSafe: TOSLightLock; // for Verify() and Sign() - not reentrant lock
fM, fE, fD, fP, fQ, fDP, fDQ, fQInv: PBigInt;
fModulusLen, fModulusBits: integer;
/// compute the Chinese Remainder Theorem (CRT) for RSA sign/decrypt
function ChineseRemainderTheorem(b: PBigInt): PBigInt;
function Pkcs1UnPad(p: PByteArray; verify: boolean): RawByteString;
function Pkcs1Pad(p: pointer; n: integer; sign: boolean): RawByteString;
public
/// initialize the RSA key context
constructor Create; override;
/// initialize and generate a new RSA key context
// - this is the main factory to generate a new RSA keypair
// - will call Create and Generate() with proper retry on rgrWeakBitsMayRetry
// - returns nil on generation error (with a silent exception)
class function GenerateNew(Bits: integer = RSA_DEFAULT_GENERATION_BITS;
Extend: TBigIntSimplePrime = RSA_DEFAULT_GENERATION_KNOWNPRIME;
Iterations: integer = RSA_DEFAULT_GENERATION_ITERATIONS;
TimeOutMS: integer = RSA_DEFAULT_GENERATION_TIMEOUTMS): TRsa;
/// finalize the RSA key context
destructor Destroy; override;
/// check if M and E fields are set
function HasPublicKey: boolean;
/// check if all fields are set, i.e. if a private key is stored
function HasPrivateKey: boolean;
/// ensure that private key stored CRT constants are mathematically coherent
// - i.e. that they are properly derived for Chinese Remainder Theorem (CRT)
function CheckPrivateKey: boolean;
/// check that the stored key match the public key stored in another TRsa
function MatchKey(RsaPublicKey: TRsa): boolean;
/// compute a genuine RSA public/private key pair of a given bit size
// - valid bit sizes are 512, 1024, 2048 (default), 3072, 4096 and 7680;
// today's minimal is 2048-bit, but you may consider 3072-bit for security
// beyond 2030, and 4096-bit have a much higher computational cost and
// 7680-bit is highly impractical (e.g. generation can be more than 30 secs)
// - since our generator is not yet officially validated by any agency,
// anything above default 2048 would not make much sense
// - searching for proper random primes may take a lot of time on low-end
// CPU so a timeout period can be supplied (default 10 secs)
// - if Iterations value is too low, the FIPS recommendation will be forced
// - on a slow CPU or with a huge number of Bits, you can increase TimeOutMS
// - hint: consider using the TRsa.GenerateNew factory , which would properly
// handle rgrWeakBitsMayRetry result
function Generate(Bits: integer = RSA_DEFAULT_GENERATION_BITS;
Extend: TBigIntSimplePrime = RSA_DEFAULT_GENERATION_KNOWNPRIME;
Iterations: integer = RSA_DEFAULT_GENERATION_ITERATIONS;
TimeOutMS: integer = RSA_DEFAULT_GENERATION_TIMEOUTMS): TRsaGenerateResult;
/// load a public key from a decoded TRsaPublicKey record
procedure LoadFromPublicKey(const PublicKey: TRsaPublicKey);
/// load a public key from raw binary buffers
// - fill M and E fields from the supplied binary buffers
procedure LoadFromPublicKeyBinary(Modulus, Exponent: pointer;
ModulusSize, ExponentSize: PtrInt);
/// load a public key from PKCS#1 DER format
// - will try and fallback to a ASN1_SEQ, as stored in a X509 certificate
function LoadFromPublicKeyDer(const Der: TCertDer): boolean;
/// load a public key from PKCS#1 PEM format
// - will also accept and try to load from the DER format if PEM failed
function LoadFromPublicKeyPem(const Pem: TCertPem): boolean;
/// load a public key from an hexadecimal E and M fields concatenation
procedure LoadFromPublicKeyHexa(const Hexa: RawUtf8);
/// load a private key from a decoded TRsaPrivateKey record
procedure LoadFromPrivateKey(const PrivateKey: TRsaPrivateKey);
/// load a private key from PKCS#1 or PKCS#8 DER format
function LoadFromPrivateKeyDer(const Der: TCertDer): boolean;
/// load a private key from PKCS#1 or PKCS#8 PEM format
// - will also accept and try to load from the DER format if PEM failed
function LoadFromPrivateKeyPem(const Pem: TCertPem): boolean;
/// save the stored public key as a TRsaPublicKey record
function SavePublicKey: TRsaPublicKey;
/// save the stored public key in PKCS#1 DER format
function SavePublicKeyDer: TCertDer;
/// save the stored public key in PKCS#1 PEM format
function SavePublicKeyPem: TCertPem;
/// save the stored private key as a TRsaPrivateKey record
// - caller should make Dest.Done once finished with the values
procedure SavePrivateKey(out Dest: TRsaPrivateKey);
/// save the stored private key in PKCS#1 DER format
function SavePrivateKeyDer: TCertDer;
/// save the stored private key in PKCS#1 PEM format
function SavePrivateKeyPem: TCertPem;
/// low-level thread-safe PKCS#1.5 buffer Decryption
// - Input should have ModulusLen bytes of data
// - returns decrypted buffer without PKCS#1.5 padding, '' on error
function Pkcs1Decrypt(Input: pointer): RawByteString;
/// low-level thread-safe PKCS#1.5 buffer Verification
// - Input should have ModulusLen bytes of data
// - returns decrypted signature without PKCS#1.5 padding, '' on error
function Pkcs1Verify(Input: pointer): RawByteString;
/// low-level thread-safe PKCS#1.5 buffer Encryption
// - InputLen should be < to ModulusLen - 11 bytes for proper padding
// - returns encrypted buffer with PKCS#1.5 padding, '' on error
function Pkcs1Encrypt(Input: pointer; InputLen: integer): RawByteString;
/// low-level thread-safe PKCS#1.5 buffer Signature
// - InputLen should be < to ModulusLen - 11 bytes for proper padding
// - returns the encrypted signature with PKCS#1.5 padding, '' on error
function Pkcs1Sign(Input: pointer; InputLen: integer): RawByteString;
/// verification of a RSA binary signature with the current Public Key
// - this method is thread-safe but blocking from several threads
function Verify(Hash: pointer; HashAlgo: THashAlgo;
const Signature: RawByteString): boolean; overload;
/// verification of a RSA binary signature with the current Public Key
// - this method is thread-safe but blocking from several threads
// - virtual method which may be overriden e.g. in TRsaPss inherited class
function Verify(Hash, Sig: pointer; HashAlgo: THashAlgo;
SigLen: integer): boolean; overload; virtual;
/// compute a RSA binary signature with the current Private Key
// - returns the encoded signature or '' on error
// - this method is thread-safe but blocking from several threads
// - virtual method which may be overriden e.g. in TRsaPss inherited class
function Sign(Hash: PHash512; HashAlgo: THashAlgo): RawByteString; virtual;
/// encrypt a message using the given Cipher and the stored public key
// - follow the EVP_SealInit/EVP_SealFinal encoding from OpenSSL and its
// EVP_PKEY.RsaSeal() wrapper from mormot.lib.openssl11
function Seal(const Message: RawByteString;
const Cipher: RawUtf8 = 'aes-128-ctr'): RawByteString; overload;
/// encrypt a message using the given Cipher and the stored public key
function Seal(Cipher: TAesAbstractClass; AesBits: integer;
const Message: RawByteString): RawByteString; overload;
/// decrypt a message using the given Cipher and the stored private key
// - follow the EVP_OpenInit/EVP_OpenFinal encoding from OpenSSL and its
// EVP_PKEY.RsaOpen() wrapper from mormot.lib.openssl11
function Open(const Message: RawByteString;
const Cipher: RawUtf8 = 'aes-128-ctr'): RawByteString; overload;
/// decrypt a message using the given Cipher and the stored private key
function Open(Cipher: TAesAbstractClass; AesBits: integer;
const Message: RawByteString): RawByteString; overload;
/// RSA modulus size in bytes
property ModulusLen: integer
read fModulusLen;
/// RSA Public key Modulus as m = p*q
property M: PBigInt
read fM;
/// RSA Public key Exponent (typically 65537)
property E: PBigInt
read fE;
/// RSA key Private Exponent
property D: PBigInt
read fD;
/// RSA Private key first Prime as p in m = p*q
property P: PBigInt
read fP;
/// RSA Private key second Prime as q in m = p*q
property Q: PBigInt
read fQ;
/// RSA Private key CRT exponent satisfying e * DP == 1 (mod (p-1))
property DP: PBigInt
read fDP;
/// RSA Private key CRT exponent satisfying e * DQ == 1 (mod (q-1))
property DQ: PBigInt
read fDQ;
/// RSA Private key CRT coefficient satisfying q * qInv == 1 (mod p)
property QInv: PBigInt
read fQInv;
published
/// RSA modulus size in bits
property ModulusBits: integer
read fModulusBits;
end;
/// meta-class of the RSA processing classes, mainly TRsa or TRsaPss
// - see e.g. CKA_TO_RSA[] global constant as a potential factory
TRsaClass = class of TRsa;
/// RSA processing class using Probabilistic Signature Scheme (PSS) signatures
// - the RSASSA-PSS signature scheme is more secure than RSASSA-PKCS1-v1_5
// - PSS encoding, originally invented by Bellare and Rogaway, is randomized
// thereby producing a different value of signature each time
// - this implementation follows RFC 8017 specifications
// - note: Open/Seal won't use RSAES-OAEP but regular RSAES-PKCS1-v1_5
TRsaPss = class(TRsa)
public
/// verification of a RSA binary signature with the current Public Key
// - overriden method using the RSASSA-PSS signature scheme
// - our implementation uses the same THashAlgo for its internal encoding,
// e.g. its MGF1 function, as recommended by RFC 8017 8.1 to prevent
// hash function substitution
// - this method is thread-safe but blocking from several threads
function Verify(Hash, Sig: pointer; HashAlgo: THashAlgo;
SigLen: integer): boolean; override;
/// compute a RSA binary signature with the current Private Key
// - overriden method using the RSASSA-PSS signature scheme
// - returns the encoded signature or '' on error
// - our implementation uses the same THashAlgo for its internal encoding
// - this method is thread-safe but blocking from several threads
function Sign(Hash: PHash512; HashAlgo: THashAlgo): RawByteString; override;
end;
/// low-level computation of the ASN.1 sequence of a hash signature
// - following RSASSA-PKCS1-v1_5 signature scheme RFC 8017 #9.2 steps 1 and 2
// - as used by TRsa.Sign() method and expected by CKM_RSA_PKCS signature
function RsaSignHashToDer(Hash: PHash512; HashAlgo: THashAlgo): TAsnObject;
function ToText(res: TRsaGenerateResult): PShortString; overload;
{ *********** Registration of our RSA Engine to the TCryptAsym Factory }
const
/// lookup to be used as convenient CKA_TO_RSA[cka].Create factory
CKA_TO_RSA: array[TCryptKeyAlgo] of TRsaClass = (
nil, // ckaNone
TRsa, // ckaRsa
TRsaPss, // ckaRsaPss
nil, // ckaEcc256
nil, // ckaEcc384
nil, // ckaEcc512
nil, // ckaEcc256k
nil); // ckaEdDSA
type
/// store a RSA public key in ICryptPublicKey format
// - using our pure pascal TRsa/TRsaPss engines of this unit
TCryptPublicKeyRsa = class(TCryptPublicKey)
protected
fRsa: TRsa;
// TCryptPublicKey.Verify overloads will call this overriden method
function VerifyDigest(Sig: pointer; Dig: THash512Rec; SigLen, DigLen: integer;
Hash: THashAlgo): boolean; override;
public
/// finalize this instance
destructor Destroy; override;
/// unserialized the public key from most known formats
function Load(Algorithm: TCryptKeyAlgo;
const PublicKeySaved: RawByteString): boolean; override;
/// as used by ICryptCert.GetKeyParams
function GetParams(out x, y: RawByteString): boolean; override;
/// use RSA sealing, i.e. encryption with this public key
function Seal(const Message: RawByteString;
const Cipher: RawUtf8): RawByteString; override;
end;
/// store a RSA private key in ICryptPrivateKey format
// - using our pure pascal TRsa/TRsaPss engines of this unit
TCryptPrivateKeyRsa = class(TCryptPrivateKey)
protected
fRsa: TRsa;
// decode the RSA private key ASN.1 and check for any associated public key
function FromDer(algo: TCryptKeyAlgo; const der: RawByteString;
pub: TCryptPublicKey): boolean; override;
// TCryptPrivateKey.Sign overloads will call this overriden method
function SignDigest(const Dig: THash512Rec; DigLen: integer;
DigAlgo: TCryptAsymAlgo): RawByteString; override;
public
/// finalize this instance
destructor Destroy; override;
/// create a new private / public key pair
// - returns the associated public key binary in SubjectPublicKey format
function Generate(Algorithm: TCryptAsymAlgo): RawByteString; override;
/// return the private key as raw binary
// - follow PKCS#8 PrivateKeyInfo encoding for RSA
function ToDer: RawByteString; override;
/// return the associated public key as stored in a X509 certificate
function ToSubjectPublicKey: RawByteString; override;
/// use EciesSeal or RSA un-sealing, i.e. decryption with this private key
function Open(const Message: RawByteString;
const Cipher: RawUtf8): RawByteString; override;
end;
implementation
{ **************** RSA Oriented Big-Integer Computation }
function Min(a, b: integer): integer;
{$ifdef HASINLINE} inline; {$endif}
begin
if a < b then
result := a
else
result := b;
end;
function Max(a, b: integer): integer;
{$ifdef HASINLINE} inline; {$endif}
begin
if a > b then
result := a
else
result := b;
end;
function CompareBI(A, B: HalfUInt): integer;
begin
result := ord(A > B) - ord(A < B);
end;
function BigIntToText(const der: TCertDer): RawUtf8;
var
b: PBigInt;
begin
with TRsaContext.Create do
try
b := LoadPermanent(der);
result := b.ToText({noclone=}true);
b.ResetPermanentAndRelease;
finally
Free;
end;
end;
function ValuesSize(bytes: integer): integer;
{$ifdef HASINLINE} inline; {$endif}
begin
result := (bytes + (HALF_BYTES - 1)) div HALF_BYTES;
end;
{ TBigInt }
procedure TBigInt.Resize(n: integer; nozero: boolean);
begin
if n = Size then
exit;
if n > Capacity then
begin
Capacity := NextGrow(n); // reserve a bit more for faster size-up
ReAllocMem(Value, Capacity * HALF_BYTES);
end;
if not nozero and
(n > Size) then
FillCharFast(Value[Size], (n - Size) * HALF_BYTES, 0);
Size := n;
end;
function TBigInt.Trim: PBigInt;
var
n: PtrInt;
begin
n := Size;
while (n > 1) and
(Value[n - 1] = 0) do // delete any leading 0
dec(n);
Size := n;
result := @self;
end;
function TBigInt.IsZero: boolean;
var
i: PtrInt;
p: PHalfUIntArray;
begin
if @self <> nil then
begin
p := Value;
if p <> nil then
begin
result := false;
for i := 0 to Size - 1 do
if p[i] <> 0 then
exit;
end;
end;
result := true;
end;
function TBigInt.IsEven: boolean;
begin
result := (Value[0] and 1) = 0;
end;
function TBigInt.IsOdd: boolean;
begin
result := (Value[0] and 1) <> 0;
end;
function TBigInt.BitIsSet(bit: PtrUInt): boolean;
begin
result := Value[bit shr HALF_SHR] and
(1 shl (bit and pred(HALF_BITS))) <> 0;
end;
function TBigInt.BitCount: integer;
var
i: PtrInt;
c: HalfUInt;
begin
result := 0;
i := Size - 1;
while Value[i] = 0 do
begin
dec(i);
if i < 0 then
exit;
end;
result := i * HALF_BITS;
c := Value[i];
repeat
inc(result);
c := c shr 1;
until c = 0;
end;
function TBigInt.BitSetCount: integer;
var
i: PtrInt;
begin
result := 0;
for i := 0 to Size - 1 do
inc(result, GetBitsCountPtrInt(Value[i]));
end;
function TBigInt.Compare(b: PBigInt; andrelease: boolean): integer;
var
i: PtrInt;
begin
result := CompareInteger(Size, b^.Size);
if result = 0 then
for i := Size - 1 downto 0 do
begin
result := CompareBI(Value[i], b^.Value[i]);
if result <> 0 then
break;
end;
if andrelease then
Release;
end;
function TBigInt.Compare(u: HalfUInt; andrelease: boolean): integer;
begin
result := CompareInteger(Size, 1);
if result = 0 then
result := CompareBI(Value[0], u);
if andrelease then
Release;
end;
function TBigInt.SetPermanent: PBigInt;
begin
if RefCnt <> 1 then
ERsaException.RaiseUtf8(
'TBigInt.SetPermanent(%): RefCnt=%', [@self, RefCnt]);
RefCnt := -1;
result := @self;
end;
function TBigInt.ResetPermanent: PBigInt;
begin
if RefCnt >= 0 then
ERsaException.RaiseUtf8(
'TBigInt.ResetPermanent(%): RefCnt=%', [@self, RefCnt]);
RefCnt := 1;
result := @self;
end;
function TBigInt.RightShift(n: integer): PBigInt;
begin
if n > 0 then
begin
dec(Size, n);
if Size <= 0 then
begin
Size := 1;
Value[0] := 0;
end
else
MoveFast(Value[n], Value[0], Size * HALF_BYTES);
end;
result := @self;