Repository navigation
Expand file tree
/
Copy pathmormot.crypt.openssl.pas
More file actions
3865 lines (3494 loc) · 127 KB
/
Copy pathmormot.crypt.openssl.pas
File metadata and controls
3865 lines (3494 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// Framework Core Cryptographic Process using OpenSSL
// - 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.openssl;
{
*****************************************************************************
High-Performance Cryptographic Features using OpenSSL 1.1 / 3.x
- OpenSSL Cryptographic Pseudorandom Number Generator (CSPRNG)
- AES Cypher/Uncypher in various Modes
- Hashers and Signers OpenSSL Wrappers
- OpenSSL Asymmetric Cryptography
- JWT Implementation using any OpenSSL Algorithm
- Register OpenSSL to our General Cryptography Catalog
*****************************************************************************
Warning: on Windows, you need to define the USE_OPENSSL conditional in YOUR
project options to have this code actually link to the OpenSSL library.
TL;DR: On x86_64, our mormot.crypt.core.pas asm is stand-alone and faster
than OpenSSL for most algorithms, and only 20% slower for AES-GCM.
For ECC/RSA, mormot.crypt.ecc/rsa are slower than OpenSSL so this
unit will override their implementation during its initialization.
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}
{$ifdef USE_OPENSSL}
// compile as a void unit if USE_OPENSSL is not defined
uses
classes,
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.os.security,
mormot.core.rtti,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.datetime,
mormot.core.variants,
mormot.lib.openssl11,
mormot.crypt.core,
mormot.crypt.ecc256r1,
mormot.crypt.secure,
mormot.crypt.jwt,
// those two units are defined here to complete their implementation
mormot.crypt.ecc,
mormot.crypt.rsa;
{ ************** OpenSSL Cryptographic Pseudorandom Number Generator (CSPRNG) }
type
/// exception class raised by the AES classes of this unit
EOpenSslCrypto = class(EOpenSsl);
/// TAesPrng-compatible class using OpenSSL
// - we abbreviate OpenSsl as Osl in class names for brevity
// - may be used instead of TAesPrng if a "proven" generator is required -
// you could override MainAesPrng global variable
// - but mormot.crypt.core TAesPrng is faster, especially for small output,
// and use a similar and proven 256-bit AES-CTR source of randomness:
// $ OpenSSL Random32 in 288.71ms i.e. 346,363/s, aver. 2us, 1.3 MB/s
// $ mORMot Random32 in 3.95ms i.e. 25,303,643/s, aver. 0us, 96.5 MB/s
// $ OpenSSL FillRandom in 240us, 397.3 MB/s
// $ mORMot FillRandom in 46us, 2 GB/s
TAesPrngOsl = class(TAesPrngAbstract)
public
/// initialize the CSPRNG using OpenSSL
// - if the library is not available, will raise an Exception
constructor Create; override;
/// wrapper around function OpenSslIsAvailable
class function IsAvailable: boolean; override;
/// fill a binary buffer with some pseudorandom data
// - this method is thread-safe
// - is just a wrapper around RAND_bytes() API call
procedure FillRandom(Buffer: pointer; Len: PtrInt); override;
/// returns the single system-wide instance of TAesPrngOsl
// - if you need to generate some random content, just call the
// TAesPrngOsl.Main.FillRandom() overloaded methods, or directly
// TAesPrngOsl.Fill() class methods
class function Main: TAesPrngAbstract; override;
end;
{ ************** AES Cypher/Uncypher in various Modes }
type
PAesOsl = ^TAesOsl;
/// reusable wrapper around OpenSSL Cipher process
{$ifdef USERECORDWITHMETHODS}
TAesOsl = record
{$else}
TAesOsl = object
{$endif USERECORDWITHMETHODS}
public
Owner: TAesAbstract;
Cipher: PEVP_CIPHER; // computed from TAesAbstractOsl.AlgoName
Ctx: array[boolean] of PEVP_CIPHER_CTX; // set and reused in CallEvp()
procedure Init(aOwner: TAesAbstract; aCipherName: PUtf8Char);
procedure Done;
procedure Clone(another: PAesOsl);
procedure SetEvp(DoEncrypt: boolean; const method: ShortString);
procedure UpdEvp(DoEncrypt: boolean; BufIn, BufOut: pointer; Count: cardinal;
KeepIV: boolean = false);
end;
/// handle AES cypher/uncypher with chaining with OpenSSL
// - we abbreviate OpenSsl as Osl in class names for brevity
// - use any of the inherited implementation, corresponding to the chaining
// mode required - TAesEcbOsl, TAesCbcOsl, TAesCfbOsl, TAesOfbOsl and TAesCtrOsl
// classes to handle in ECB, CBC, CFB, OFB and CTR mode (including PKCS7-like padding)
// - those classes are re-entrant, i.e. that you can call the Encrypt*
// or Decrypt* methods on the same instance several times
TAesAbstractOsl = class(TAesAbstract)
protected
fAes: TAesOsl;
procedure AfterCreate; override; // circumvent Delphi bug about const aKey
public
/// creates a new instance with the very same values
// - directly copy the existing OpenSSL context for efficiency
function Clone: TAesAbstract; override;
/// compute a class instance similar to this one, for performing the
// reverse encryption/decryption process
// - will return self to avoid creating two instances
function CloneEncryptDecrypt: TAesAbstract; override;
/// release the used instance memory and resources
destructor Destroy; override;
/// wrapper around function OpenSslIsAvailable
// - actual cipher won't be checked until Create() since we need the keysize
class function IsAvailable: boolean; override;
/// perform the AES cypher in the corresponding mode
procedure Encrypt(BufIn, BufOut: pointer; Count: cardinal); override;
/// perform the AES un-cypher in the corresponding mode
procedure Decrypt(BufIn, BufOut: pointer; Count: cardinal); override;
end;
/// OpenSSL AES cypher/uncypher without chaining (ECB)
// - this mode is known to be less secure than the others, and should not be
// needed in practice, but from some legacy / unsafe purposes
TAesEcbOsl = class(TAesAbstractOsl)
protected
procedure AfterCreate; override;
end;
/// OpenSSL AES cypher/uncypher with Cipher-block chaining (CBC)
// - on x86_64, our TAesCbc class is slower than OpenSSL 3.0:
// $ mormot aes-128-cbc in 4.48ms i.e. 544.9K/s or 1.1 GB/s
// $ mormot aes-256-cbc in 5.46ms i.e. 446.9K/s or 0.9 GB/s
// $ openssl aes-128-cbc in 3.23ms i.e. 755.6K/s or 1.6 GB/s
// $ openssl aes-256-cbc in 4.04ms i.e. 602.9K/s or 1.2 GB/s
TAesCbcOsl = class(TAesAbstractOsl)
protected
procedure AfterCreate; override;
end;
/// OpenSSL AES cypher/uncypher with Cipher feedback (CFB)
// - on x86_64, our TAesCfb class is really faster than OpenSSL 3.0:
// $ mormot aes-128-cfb in 2.64ms i.e. 0.9M/s or 1.9 GB/s
// $ mormot aes-256-cfb in 3.48ms i.e. 700.7K/s or 1.4 GB/s
// $ openssl aes-128-cfb in 4.95ms i.e. 492.4K/s or 1 GB/s
// $ openssl aes-256-cfb in 5.80ms i.e. 420.6K/s or 0.9 GB/s
TAesCfbOsl = class(TAesAbstractOsl)
protected
procedure AfterCreate; override;
end;
/// OpenSSL AES cypher/uncypher with Output feedback (OFB)
// - on x86_64, our TAesOfb class is faster than OpenSSL 1.1:
// $ mormot aes-128-ofb in 2.62ms i.e. 0.9M/s or 1.9 GB/s
// $ mormot aes-256-ofb in 3.49ms i.e. 699.3K/s or 1.4 GB/s
// $ openssl aes-128-ofb in 3.49ms i.e. 698.7K/s or 1.4 GB/s
// $ openssl aes-256-ofb in 4.36ms i.e. 558.8K/s or 1.1 GB/s
TAesOfbOsl = class(TAesAbstractOsl)
protected
procedure AfterCreate; override;
end;
/// OpenSSL AES cypher/uncypher with 128-bit Counter mode (CTR)
// - similar to TAesCtrNist, not our proprietary TAesCtrAny with a 64-bit CTR
// - our TAesCtrNist class is faster than OpenSSL on x86_64:
// $ mormot aes-128-ctr in 596us i.e. 4M/s or 8.7 GB/s
// $ mormot aes-256-ctr in 716us i.e. 3.3M/s or 7.2 GB/s
// $ openssl aes-128-ctr in 1.13ms i.e. 2.1M/s or 4.5 GB/s
// $ openssl aes-256-ctr in 1.27ms i.e. 1.8M/s or 4 GB/s
// - on i386, numbers shows that our own 4x interleaved asm works great
// (here in comparison with OpenSSL 3.5 on Win32):
// $ mormot aes-128-ctr in 644us i.e. 3.7M/s or 8 GB/s
// $ mormot aes-256-ctr in 836us i.e. 2.8M/s or 6.2 GB/s
// $ openssl aes-128-ctr in 1.52ms i.e. 1.5M/s or 3.4 GB/s
// $ openssl aes-256-ctr in 1.68ms i.e. 1.4M/s or 3 GB/s
TAesCtrOsl = class(TAesAbstractOsl)
protected
procedure AfterCreate; override;
end;
/// OpenSSL AES-GCM cypher/uncypher
// - implements AEAD (authenticated-encryption with associated-data) process
// via MacSetNonce/MacEncrypt or AesGcmAad/AesGcmFinal methods
// - our TAesGcm class is 8x interleaved for both GMAC and AES-CTR on x86_64,
// and noticeably faster than OpenSSL 3.0 (for small buffers):
// $ mormot aes-128-gcm in 1.03ms i.e. 2.3M/s or 5 GB/s
// $ mormot aes-256-gcm in 1.18ms i.e. 2M/s or 4.4 GB/s
// $ openssl aes-128-gcm in 2.50ms i.e. 0.9M/s or 2 GB/s
// $ openssl aes-256-gcm in 2.64ms i.e. 0.9M/s or 1.9 GB/s
// - on i386, mormot numbers are only slightly lower than OpenSSL after 2KB,
// but still much faster for small blocks:
// $ mormot aes-128-gcm in 5.18ms i.e. 470.8K/s or 1 GB/s
// $ mormot aes-256-gcm in 5.34ms i.e. 456.5K/s or 0.9 GB/s
// $ openssl aes-128-gcm in 3.83ms i.e. 635.9K/s or 1.3 GB/s
// $ openssl aes-256-gcm in 4.02ms i.e. 606.4K/s or 1.2 GB/s
// 50 bytes:
// $ mormot aes-128-gcm in 97us i.e. 4.9M/s, aver. 194ns, 245.7 MB/s
// $ mormot aes-256-gcm in 102us i.e. 4.6M/s, aver. 204ns, 233.7 MB/s
// $ openssl aes-128-gcm in 515us i.e. 0.9M/s, aver. 1.03us, 46.2 MB/s
// $ openssl aes-256-gcm in 541us i.e. 0.8M/s, aver. 1.08us, 44 MB/s
TAesGcmOsl = class(TAesGcmAbstract)
protected
fAes: TAesOsl;
function AesGcmInit: boolean; override; // from fKey/fKeySize
procedure AesGcmClone(another: TAesGcmAbstract); override;
procedure AesGcmDone; override;
procedure AesGcmReset; override; // from fIV/CTR_POS
function AesGcmProcess(BufIn, BufOut: pointer; Count: cardinal): boolean; override;
public
/// wrapper around function OpenSslIsAvailable
// - actual cipher won't be checked until Create() since we need the keysize
class function IsAvailable: boolean; override;
/// compute a class instance similar to this one, for performing the
// reverse encryption/decryption process
// - will return self to avoid creating two instances
function CloneEncryptDecrypt: TAesAbstract; override;
/// AES-GCM pure alternative to MacSetNonce() - unsupported
// - set the IV as usual (only the first 12 bytes will be used for GCM),
// then optionally append any AEAD data with this method; warning: you need
// to call Encrypt() once before - perhaps as Encrypt(nil, nil, 0)
procedure AesGcmAad(Buf: pointer; Len: integer); override;
/// AES-GCM pure alternative to MacEncryptGetTag/MacDecryptCheckTag
// - after Encrypt, fill tag with the GCM value of the data and return true
// - after Decrypt, return true only if the GCM value of the data match tag
function AesGcmFinal(var Tag: TAesBlock; TagLen: integer): boolean; override;
end;
{ ************** Hashers and Signers OpenSSL Wrappers }
type
/// exception class raised by the hashing classes of this unit
EOpenSslHash = class(EOpenSsl);
/// abstract parent multi-algorithm hashing/HMAC wrapper for OpenSSL
TOpenSslDigestAbstract = class
private
fDigestSize: cardinal;
fDigestValue: THash512Rec;
public
/// wrapper around function OpenSslIsAvailable
class function IsAvailable: boolean;
/// call this method for each continuous message block
// - iterate over all message blocks, then call Digest to retrieve the HMAC
procedure Update(Data: pointer; DataLength: integer); overload; virtual; abstract;
/// call this method for each continuous message block
procedure Update(const Data: RawByteString); overload;
{$ifdef HASINLINE}inline;{$endif}
/// computes the hash of all supplied messages
// - store it internally the DigestValue buffer, or copy it into Dest buffer
// which is typically a THash256 or THash512 variable
// - returns actual DigestValue/Dest buffer length, i.e. DigestSize
function Digest(Dest: pointer = nil): cardinal; virtual; abstract;
/// computes the Hash/HMAC of all supplied message as lowercase hexa chars
function DigestHex: RawUtf8;
/// raw access to the final Message Digest, after a call to the Digest method
// - if HashSize as supplied to Create() is bigger than 64, first bytes will
// be truncated in this field - you should specify a buffer to Digest() call
property DigestValue: THash512Rec
read fDigestValue;
/// how many bytes have been stored in DigestValues, after a call to Digest
property DigestSize: cardinal
read fDigestSize;
end;
/// convenient multi-algorithm wrapper for OpenSSL Hash algorithms
TOpenSslHash = class(TOpenSslDigestAbstract)
private
fCtx: PEVP_MD_CTX;
fXof: boolean;
procedure Init(MD: PEVP_MD; HashSize: cardinal);
public
/// initialize the internal hashing structure for a specific algorithm
// - for XOF hash functions such as 'shake256', the hashSize option
// can be used to specify the desired output length in bytes
constructor Create(Algorithm: THashAlgo; HashSize: cardinal = 0); overload;
/// initialize the internal hashing structure for a specific algorithm
// - Algorithm is one of "openssl list -digest-algorithms"
// - if Algorithm is not specified, EVP_sha256 (aka 'sha256') will be used
// - for XOF hash functions such as 'shake256', the hashSize option
// can be used to specify the desired output length in bytes
// - raise an EOpenSslHash exception on unknown/unsupported algorithm
constructor Create(const Algorithm: RawUtf8; HashSize: cardinal = 0); overload;
/// call this method for each continuous message block
// - iterate over all message blocks, then call Digest to retrieve the Hash
procedure Update(Data: pointer; DataLength: integer); override;
/// computes the hash of all supplied messages
// - store it internally the DigestValue buffer, or copy it into Dest buffer
// which is typically a THash256 or THash512 variable
// - returns actual DigestValue/Dest buffer length, i.e. DigestSize
function Digest(Dest: pointer = nil): cardinal; override;
/// compute the message authentication code using the supplied hash function
class function Hash(Algorithm: THashAlgo; const Data: RawByteString;
HashSize: cardinal = 0): RawUtf8; overload;
/// compute the message authentication code using "Algorithm" OpenSSL digest
class function Hash(const Algorithm: RawUtf8; const Data: RawByteString;
HashSize: cardinal = 0): RawUtf8; overload;
/// release the digest context
destructor Destroy; override;
end;
/// convenient multi-algorithm wrapper for OpenSSL HMAC algorithms
TOpenSslHmac = class(TOpenSslDigestAbstract)
private
fCtx: PHMAC_CTX;
procedure Init(md: PEVP_MD; Key: pointer; KeyLength: cardinal);
public
/// initialize the internal HMAC structure for a specific Algorithm and Key
// - Key/KeyLen define the HMAC associated salt
constructor Create(Algorithm: THashAlgo; Key: pointer; KeyLength: cardinal); overload;
/// initialize the internal HMAC structure for a specific Algorithm and Key
// - Algorithm is one of "openssl list -digest-algorithms"
// - if Algorithm is not specified, EVP_sha256 (aka 'sha256') will be used
// - Key/KeyLen define the HMAC associated salt
// - raise an EOpenSslHash exception on unknown/unsupported algorithm
constructor Create(const Algorithm: RawUtf8;
Key: pointer; KeyLength: cardinal); overload;
/// initialize the internal HMAC structure for a specific Algorithm and Key
constructor Create(const Algorithm: RawUtf8;
const Key: RawByteString); overload;
/// call this method for each continuous message block
// - iterate over all message blocks, then call Digest to retrieve the Hash
procedure Update(Data: pointer; DataLength: integer); override;
/// computes the HMAC of all supplied messages
// - store it internally the DigestValue buffer, or copy it into Dest buffer
// which is typically a THash256 or THash512 variable
// - returns actual DigestValue/Dest buffer length, i.e. DigestSize
function Digest(Dest: pointer = nil): cardinal; override;
/// compute the HMAC using "Algorithm" OpenSSL digest (e.g. 'sha256')
class function Hmac(const Algorithm: RawUtf8; const Data: RawByteString;
Key: pointer; KeyLength: cardinal): RawUtf8; overload;
/// compute the HMAC using "Algorithm" OpenSSL digest (e.g. 'sha256')
class function Hmac(const Algorithm: RawUtf8;
const Data, Key: RawByteString): RawUtf8; overload;
/// compute the HMAC using the supplied hash function
class function Hmac(Algorithm: THashAlgo;
const Data: RawByteString; Key: pointer; KeyLength: cardinal): RawUtf8; overload;
/// compute the HMAC using the supplied hash function
class function Hmac(Algorithm: THashAlgo;
const Data, Key: RawByteString): RawUtf8; overload;
/// release the digest context
destructor Destroy; override;
end;
/// retrieve a low-level PEVP_MD digest from its algorithm name
// - raise an EOpenSslHash if this algorithm is not found
function OpenSslGetMdByName(const Algorithm: RawUtf8;
const Caller: ShortString): PEVP_MD; overload;
/// retrieve a low-level PEVP_MD digest from mORMot THashAlgo enum
// - returns nil if not found, e.g. if OpenSsl is not available
function OpenSslGetMd(Algorithm: THashAlgo): PEVP_MD; overload;
/// retrieve a low-level PEVP_MD digest from mORMot TCryptAsymAlgo enum
// - returns nil if not found, e.g. if OpenSsl is not available
function OpenSslGetMd(Algorithm: TCryptAsymAlgo): PEVP_MD; overload;
{ ************** OpenSSL Asymmetric Cryptography }
type
/// exception class raised by the sign/verify classes of this unit
EOpenSslAsymmetric = class(EOpenSsl);
/// asymmetric digital signature of some Message using a given PrivateKey
// - if Algorithm is '', EVP_sha256 will be used as message Digest
// - if Algorithm is 'null', no Digest is done before signature - which is
// mandatory e.g. for ed25519 which uses internally SHA-512
// - returns 0 on error, or the result Signature size in bytes
function OpenSslSign(const Algorithm: RawUtf8;
Message, PrivateKey: pointer; MessageLen, PrivateKeyLen: integer;
out Signature: RawByteString; const PrivateKeyPassword: SpiUtf8 = ''): cardinal;
/// asymmetric digital verification of some Message using a given PublicKey
// - if Algorithm is '', EVP_sha256 will be used as message Digest
// - if Algorithm is 'null', no Digest is done before signature - which is
// mandatory e.g. for ed25519 which uses internally SHA-512
// - returns false on error, or true if the Message has been authenticated
function OpenSslVerify(const Algorithm: RawUtf8; const PublicKeyPassword: SpiUtf8;
Message, PublicKey, Signature: pointer;
MessageLen, PublicKeyLen, SignatureLen: integer;
const Engine: RawUtf8 = ''): boolean;
/// check if an OpenSSL given type of public/private pair of keys is supported
// - some older OpenSSL versions do not support e.g. EVP_PKEY_ED25519
function OpenSslSupports(EvpType: integer): boolean; overload;
/// check if a TCryptAsymAlgo of public/private pair of keys is supported
function OpenSslSupports(Algo: TCryptAsymAlgo): boolean; overload;
/// generate a public/private pair of keys in raw OpenSSL format
// - if EvpType is EVP_PKEY_DSA, EVP_PKEY_DH or EVP_PKEY_RSA or EVP_PKEY_RSA_PSS,
// BitsOrCurve is the number of bits of the key
// - if EvpType is EVP_PKEY_EC, BitsOrCurve is the curve NID (e.g.
// NID_X9_62_prime256v1)
// - if EvpType is EVP_PKEY_ED25519, BitsOrCurve is ignored
// - caller should result.Free once done with the private key returned instance
function OpenSslGenerateKeys(EvpType, BitsOrCurve: integer): PEVP_PKEY; overload;
/// generate a public/private pair of keys in PEM text format
// - if EvpType is EVP_PKEY_DSA, EVP_PKEY_DH or EVP_PKEY_RSA or EVP_PKEY_RSA_PSS,
// BitsOrCurve is the number of bits of the key
// - if EvpType is EVP_PKEY_EC, BitsOrCurve is the Elliptic curve NID (e.g.
// NID_X9_62_prime256v1)
// - if EvpType is EVP_PKEY_ED25519, BitsOrCurve is ignored
procedure OpenSslGenerateKeys(EvpType, BitsOrCurve: integer;
out PrivateKey, PublicKey: RawUtf8; const PrivateKeyPassWord: SpiUtf8 = ''); overload;
/// generate a public/private pair of keys in raw DER binary format
// - if EvpType is EVP_PKEY_DSA, EVP_PKEY_DH or EVP_PKEY_RSA or EVP_PKEY_RSA_PSS,
// BitsOrCurve is the number of bits of the key
// - if EvpType is EVP_PKEY_EC, BitsOrCurve is the Elliptic curve NID (e.g.
// NID_X9_62_prime256v1)
// - if EvpType is EVP_PKEY_ED25519, BitsOrCurve is ignored
procedure OpenSslGenerateBinaryKeys(EvpType, BitsOrCurve: integer;
out PrivateKey, PublicKey: RawByteString; const PrivateKeyPassWord: SpiUtf8 = '');
/// load a public key from its raw binary parameters, e.g. from JWK fields
// - if EvpType is EVP_PKEY_RSA or EVP_PKEY_RSA_PSS BitsOrCurve is the number of
// bits of the key
// - if EvpType is EVP_PKEY_EC, BitsOrCurve is the Elliptic curve NID (e.g.
// - for ECC, returns the x,y coordinates
// - for RSA, x is set to the Exponent (e), and y to the Modulus (n)
// - caller should make result.Free once done with the result
function OpenSslLoadPublicKeyFromParams(EvpType, BitsOrCurve: integer;
const X, Y: RawByteString): PEVP_PKEY; overload;
/// load a public key from its raw binary parameters, e.g. from JWK fields
// - for ECC, returns the x,y coordinates
// - for RSA, x is set to the Exponent (e), and y to the Modulus (n)
// - caller should make result.Free once done with the result
function OpenSslLoadPublicKeyFromParams(algo: TCryptKeyAlgo;
const x, y: RawByteString): PEVP_PKEY; overload;
/// load a RSA or ECC public key from JWK JSON content
// - caller should make result.Free once done with the result
// - if algo is ckaNone, the proper algorithm will be guessed from "kty" (+"crv")
function OpenSslLoadPublicKeyFromJwk(const jwk: RawUtf8; algo: TCryptKeyAlgo = ckaNone): PEVP_PKEY;
{
/// compute the (e.g. ECDH) shared secret from a public/private keys inverted pair
function OpenSslSharedSecret(EvpType, BitsOrCurve: integer;
const PublicKey, PrivateKey: RawUtf8; const PrivateKeyPassword: SpiUtf8 = ''): RawByteString;
}
/// mormot.crypt.ecc256r1 compatible function for asymmetric key generation
// - this OpenSSL-powered function will replace our slower mormot.crypt.ecc256r1
// $ OpenSSL: 300 Ecc256r1MakeKey in 7.75ms i.e. 38,664/s, aver. 25us
// $ mORMot: 300 Ecc256r1MakeKey in 255ms i.e. 1,176/s, aver. 850us
// - directly access OpenSSL prime256v1, so faster than OpenSslGenerateKeys()
function ecc_make_key_osl(out PublicKey: TEccPublicKey;
out PrivateKey: TEccPrivateKey): boolean;
/// mormot.crypt.ecc256r1 compatible function for asymmetric key signature
// - this OpenSSL-powered function will replace our slower pascal/c code
// $ OpenSSL: 300 Ecc256r1Sign in 11.66ms i.e. 25,711/s, aver. 38us
// $ mORMot: 300 Ecc256r1Sign in 262.72ms i.e. 1,141/s, aver. 875us
// - directly access OpenSSL prime256v1, so faster than OpenSslSign()
function ecdsa_sign_osl(const PrivateKey: TEccPrivateKey; const Hash: TEccHash;
out Signature: TEccSignature): boolean;
/// mormot.crypt.ecc256r1 compatible function for asymmetric key verification
// - this OpenSSL-powered function will replace our slower pascal/c code
// $ OpenSSL: 300 Ecc256r1Verify in 41.32ms i.e. 7,260/s, aver. 137us
// $ mORMot: 300 Ecc256r1Verify in 319.32ms i.e. 939/s, aver. 1.06ms
// - directly access OpenSSL prime256v1, so faster than OpenSslVerify()
function ecdsa_verify_osl(const PublicKey: TEccPublicKey; const Hash: TEccHash;
const Signature: TEccSignature): boolean;
/// mormot.crypt.ecc256r1 compatible function for ECDH shared secret computation
// - this OpenSSL-powered function will replace our slower pascal/c code
// $ OpenSSL: 598 Ecc256r1SharedSecret in 67.98ms i.e. 8,796/s, aver. 113us
// $ mORMot: 598 Ecc256r1SharedSecret in 537.95ms i.e. 1,111/s, aver. 899us
function ecdh_shared_secret_osl(const PublicKey: TEccPublicKey;
const PrivateKey: TEccPrivateKey; out Secret: TEccSecretKey): boolean;
type
/// OpenSSL verification of a ECDSA signature using ECC secp256r1 cryptography
// - assigned to TEcc256r1Verify global meta-class at startup
TEcc256r1VerifyOsl = class(TEcc256r1VerifyAbstract)
protected
fKey: PEC_KEY;
fPoint: PEC_POINT;
public
/// initialize the verifier with a given ECC compressed public key
constructor Create(const pub: TEccPublicKey); override;
/// finalize this instance
destructor Destroy; override;
/// validate a signature against a hash using ECC
function Verify(const hash: TEccHash; const sign: TEccSignature): boolean;
override;
end;
const
CAA_EVPTYPE: array[TCryptAsymAlgo] of integer = (
EVP_PKEY_EC, // caaES256
EVP_PKEY_EC, // caaES384
EVP_PKEY_EC, // caaES512
EVP_PKEY_EC, // caaES256K
EVP_PKEY_RSA, // caaRS256
EVP_PKEY_RSA, // caaRS384
EVP_PKEY_RSA, // caaRS512
EVP_PKEY_RSA_PSS, // caaPS256
EVP_PKEY_RSA_PSS, // caaPS384
EVP_PKEY_RSA_PSS, // caaPS512
EVP_PKEY_ED25519); // caaEdDSA
var
/// the default parameters used for keys generation
// - use OpenSslDefaultRsaBits() to change RSA keysize globally for OpenSSL
CAA_BITSORCURVE: array[TCryptAsymAlgo] of integer = (
NID_X9_62_prime256v1, // caaES256
NID_secp384r1, // caaES384
NID_secp521r1, // caaES512
NID_secp256k1, // caaES256K
RSA_DEFAULT_GENERATION_BITS, // caaRS256
RSA_DEFAULT_GENERATION_BITS, // caaRS384
RSA_DEFAULT_GENERATION_BITS, // caaRS512
RSA_DEFAULT_GENERATION_BITS, // caaPS256
RSA_DEFAULT_GENERATION_BITS, // caaPS384
RSA_DEFAULT_GENERATION_BITS, // caaPS512
0); // caaEdDSA
{ ************** JWT Implementation using any OpenSSL Algorithm }
type
/// abstract parent for OpenSSL JWT algorithms - never use this plain class!
TJwtOpenSsl = class(TJwtAsym)
protected
fPrivateKey, fPublicKey: RawByteString;
fPrivateKeyPassword, fPublicKeyPassword: SpiUtf8;
fHashAlgorithm: RawUtf8;
fGenEvpType: integer;
fGenBitsOrCurve: integer;
fAlgoMd: PEVP_MD;
fPrivKey, fPubKey: PEVP_PKEY;
fAsymAlgo: TCryptAsymAlgo;
function ComputeSignature(const headpayload: RawUtf8): RawUtf8; override;
function CheckSignature(headpayload: PValuePUtf8Char;
const signature: RawByteString): TJwtResult; override;
public
/// initialize the JWT processing instance using any supported OpenSSL algorithm
constructor Create(const aJwtAlgorithm, aHashAlgorithm: RawUtf8;
aGenEvpType, aGenBitsOrCurve: integer;
const aPrivateKey, aPublicKey: RawByteString;
const aPrivateKeyPassword, aPublicKeyPassword: SpiUtf8;
aClaims: TJwtClaims; const aAudience: array of RawUtf8;
aExpirationMinutes: integer = 0; aIDIdentifier: TSynUniqueIdentifierProcess = 0;
aIDObfuscationKey: RawUtf8 = ''; aIDObfuscationKeyNewKdf: integer = 0);
reintroduce;
/// finalize the instance
destructor Destroy; override;
/// wrapper around OpenSslIsAvailable() function
class function IsAvailable: boolean; virtual;
/// the OpenSSL hash algorithm, as supplied to the constructor
property HashAlgorithm: RawUtf8
read fHashAlgorithm;
/// the asymmetric algorithm, as defined by inherted classes
property AsymAlgo: TCryptAsymAlgo
read fAsymAlgo;
end;
/// abstract parent for OpenSSL JWT algorithms - never use this plain class!
// - inherited classes implement all official algorithms from https://jwt.io
// - we abbreviate OpenSsl as Osl in class names for brevity
// - some numbers from our regresssion tests on Linux x86_64 for JWT validation:
// $ 100 RS256 in 2.03ms i.e. 47.8K/s, aver. 20us
// $ 100 RS384 in 1.99ms i.e. 48.9K/s, aver. 19us
// $ 100 RS512 in 1.99ms i.e. 48.9K/s, aver. 19us
// $ 100 PS256 in 2.30ms i.e. 42.3K/s, aver. 23us
// $ 100 PS384 in 2.26ms i.e. 43.1K/s, aver. 22us
// $ 100 PS512 in 2.75ms i.e. 35.4K/s, aver. 27us
// $ 100 ES256 in 8.64ms i.e. 11.3K/s, aver. 86us
// $ 100 ES384 in 81.43ms i.e. 1.1K/s, aver. 814us
// $ 100 ES512 in 59.81ms i.e. 1.6K/s, aver. 598us
// $ 100 ES256K in 40.43ms i.e. 2.4K/s, aver. 404us
// $ 100 EdDSA in 11.55ms i.e. 8.4K/s, aver. 115us
TJwtAbstractOsl = class(TJwtOpenSsl)
protected
// fAlgorithm+fAsymAlgo+fHashAlgorithm+fGenEvpType+fGenBitsOrCurve from GetAsymAlgo
procedure SetAlgorithms; virtual;
public
/// initialize the JWT processing instance calling SetAlgorithms abstract method
// - the supplied key(s) could be in PEM or raw DER binary format
// - the supplied set of claims are expected to be defined in the JWT payload
// - aAudience are the allowed values for the jrcAudience claim
// - aExpirationMinutes is the deprecation time for the jrcExpirationTime claim
// - aIDIdentifier and aIDObfuscationKey/aIDObfuscationKeyNewKdf are passed
// to a TSynUniqueIdentifierGenerator instance used for jrcJwtID claim
constructor Create(
const aPrivateKey, aPublicKey: RawByteString;
const aPrivateKeyPassword, aPublicKeyPassword: SpiUtf8;
aClaims: TJwtClaims; const aAudience: array of RawUtf8;
aExpirationMinutes: integer = 0; aIDIdentifier: TSynUniqueIdentifierProcess = 0;
aIDObfuscationKey: RawUtf8 = ''; aIDObfuscationKeyNewKdf: integer = 0);
reintroduce;
/// generate a private/public keys pair for this algorithm in PEM text format
// - the new key will have RSA_DEFAULT_GENERATION_BITS, i.e. 2048-bit
class procedure GenerateKeys(out PrivateKey, PublicKey: RawUtf8);
/// generate a private/public keys pair for this algorithm in raw DER format
// - the new key will have RSA_DEFAULT_GENERATION_BITS, i.e. 2048-bit
class procedure GenerateBinaryKeys(out PrivateKey, PublicKey: RawByteString);
/// wrapper around OpenSslSupports() function
class function IsAvailable: boolean; override;
end;
/// meta-class of all OpenSSL JWT algorithms
TJwtAbstractOslClass = class of TJwtAbstractOsl;
/// implements 'ES256' secp256r1 ECC algorithm over SHA-256 using OpenSSL
// - note that our TJwtEs256 class is slightly faster on Linux x86_64:
// $ TJwtEs256 pascal: 100 ES256 in 33.57ms i.e. 2.9K/s, aver. 335us
// $ TJwtEs256 OpenSSL: 100 ES256 in 6.90ms i.e. 14.1K/s, aver. 69us
// $ TJwtEs256Osl: 100 ES256 in 8.64ms i.e. 11.3K/s, aver. 86us
TJwtEs256Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'ES384' secp384r1 ECC algorithm over SHA-384 using OpenSSL
TJwtEs384Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'ES512' ecp521r1 ECC algorithm over SHA-512 using OpenSSL
TJwtEs512Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'ES256K' secp256k1 ECC algorithm using OpenSSL
TJwtEs256KOsl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'RS256' RSA algorithm over SHA-256 using OpenSSL
TJwtRs256Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'RS384' RSA algorithm over SHA-384 using OpenSSL
TJwtRs384Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'RS512' RSA algorithm over SHA-512 using OpenSSL
TJwtRs512Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'PS256' RSA-PSS algorithm over SHA-256 using OpenSSL
TJwtPs256Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'PS384' RSA-PSS algorithm over SHA-384 using OpenSSL
TJwtPs384Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'PS512' RSA-PSS algorithm over SHA-512 using OpenSSL
TJwtPs512Osl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
/// implements 'EdDSA' Ed25519 algorithm using OpenSSL
TJwtEddsaOsl = class(TJwtAbstractOsl)
public
class function GetAsymAlgo: TCryptAsymAlgo; override;
end;
{ ************** Register OpenSSL to our General Cryptography Catalog }
/// guess the asymmetric algorithm of this OpenSSL X.509 certificate
// - returns nil if x is nil
// - raise an EOpenSslCert if x has an unsupported algorithm
// - warning: caaES256K can not be distinguished from caaES256
// - is defined here because TCryptAsymAlgo is from mormot.crypt.secure.pas
// which does not fit in the low-level mormot.lib.openssl.pas unit
function X509Algo(x: PX509): TCryptAsymAlgo;
/// compute a new ICryptCert OpenSSL instance from DER or PEM input
// - returns nil if the input is not correct or not supported
// - returns non-nil TCryptCertOpenSsl instance from function LoadCertificate()
// - will guess the proper TCryptCertAlgoOpenSsl to use for the ICryptCert
// - called e.g. by TCryptCertCacheOpenSsl
function OpenSslLoad(const Cert: RawByteString): ICryptCert;
function ToText(u: TX509Usage): RawUtf8; overload;
function ToText(u: TX509Usages): ShortString; overload;
{$ifdef HASINLINE} inline; {$endif}
/// high-level function to decode X.509 certificate main properties using OpenSSL
// - assigned to mormot.core.secure X509Parse() redirection by RegisterOpenSsl
function OpenSslX509Parse(const Cert: RawByteString; out Info: TX509Parsed): boolean;
/// globally override default RSA_DEFAULT_GENERATION_BITS = 2048 for OpenSSL
// - set at runtime after RegisterOpenSsl - expects bits = 2048/3072/4096/7680/8192
// - updates global CAA_BITSORCURVE[] and existing CryptAsymOpenSsl[] classes
procedure OpenSslDefaultRsaBits(bits: integer);
/// call once at program startup to use OpenSSL when its performance matters
// - to be typically called after function OpenSslInitialize() by your project
// - redirects TAesGcmFast (and TAesCtrFast on i386) globals to OpenSSL
// - redirects raw mormot.crypt.ecc256r1 functions to use OpenSSL which is much
// faster than our stand-alone pure pascal version
// - register OpenSSL for our Asym() and Cert() high-level factory, and
// also for CryptPublicKey[] and CryptPrivateKey[]
// - RegisterX509 from mormot.crypt.x509.pas can be called after this procedure,
// to register TCryptCertAlgoX509 with ckaEcc384, ckaEcc512 and ckaEdDSA
procedure RegisterOpenSsl;
type
/// store an OpenSSL public key in ICryptPublicKey format
// - set to mormot.crypt.secure CryptPublicKey[] factories by RegisterOpenSsl
TCryptPublicKeyOpenSsl = class(TCryptPublicKey)
protected
fPubKey: PEVP_PKEY;
public
destructor Destroy; override;
function Load(Algorithm: TCryptKeyAlgo;
const PublicKeySaved: RawByteString): boolean; override;
function Verify(Algorithm: TCryptAsymAlgo;
Data, Sig: pointer; DataLen, SigLen: integer): boolean; overload; override;
function GetParams(out x, y: RawByteString): boolean; override;
function Seal(const Message: RawByteString;
const Cipher: RawUtf8): RawByteString; override;
end;
/// store an OpenSSL private key in ICryptPrivateKey format
// - set to mormot.crypt.secure CryptPrivateKey[] factories by RegisterOpenSsl
TCryptPrivateKeyOpenSsl = class(TCryptPrivateKey)
protected
fPrivKey: PEVP_PKEY;
public
destructor Destroy; override;
function Load(Algorithm: TCryptKeyAlgo; const AssociatedKey: ICryptPublicKey;
const PrivateKeySaved: RawByteString; const Password: SpiUtf8): boolean; override;
function Save(AsPem: boolean; const Password: SpiUtf8): RawByteString; override;
function Generate(Algorithm: TCryptAsymAlgo): RawByteString; override;
function Sign(Algorithm: TCryptAsymAlgo;
Data: pointer; DataLen: integer): RawByteString; overload; override;
function ToDer: RawByteString; override;
function ToSubjectPublicKey: RawByteString; override;
function Open(const Message: RawByteString;
const Cipher: RawUtf8): RawByteString; override;
function SharedSecret(const PeerKey: ICryptPublicKey): RawByteString;
override;
end;
/// maintain a cache of OpenSSL X.509 ICryptCert instances, from their DER/binary
// - defined here so that you could use OpenSSL for your certificates process
TCryptCertCacheOpenSsl = class(TCryptCertCache)
protected
// overidden to call OpenSslLoad() and return a TCryptCertOpenSsl
function InternalLoad(const Cert: RawByteString): ICryptCert; override;
end;
{
NOTICE:
- the algorithms of this unit are available as 'x509-es256' to 'x509-ps256',
and 'x509-store'
- mormot.crypt.secure exposes CryptCertOpenSsl[] and CryptStoreOpenSsl globals
- will override the 'x509-*' algorithms from mormot.crypt.x509
- the 'x509-store' is not fully compliant with RFC recommendations, due to
restrictions on the OpenSSL store internals, so 'x509-pki' store from
mormot.crypt.x509 is likely to be preferred
}
implementation
{ TAesOsl }
procedure TAesOsl.Init(aOwner: TAesAbstract; aCipherName: PUtf8Char);
begin
Owner := aOwner;
EOpenSslCrypto.CheckAvailable(PClass(Owner)^, 'Create');
Cipher := EVP_get_cipherbyname(aCipherName);
if Cipher = nil then
EOpenSslCrypto.RaiseFmt(Owner, 'Create: unknown ''%s'' cipher', [aCipherName]);
end;
procedure TAesOsl.Done;
begin
if Ctx[false] <> nil then
EVP_CIPHER_CTX_free(Ctx[false]);
if Ctx[true] <> nil then
EVP_CIPHER_CTX_free(Ctx[true]);
end;
procedure TAesOsl.Clone(another: PAesOsl);
var
enc: boolean;
begin // another^.Owned is set by the caller
another^.Cipher := Cipher;
for enc := false to true do
if Ctx[enc] <> nil then
begin
// efficient Ctx[] copy
another^.Ctx[enc] := EVP_CIPHER_CTX_new;
EVP_CIPHER_CTX_copy(another^.Ctx[enc], Ctx[enc]);
end;
end;
procedure TAesOsl.SetEvp(DoEncrypt: boolean; const method: ShortString);
var
c: PEVP_CIPHER_CTX;
begin
c := Ctx[DoEncrypt];
if (c <> nil) and
(Owner.AlgoMode = mGcm) and
(OpenSslVersion >= $30000000) then
// on OpenSSL 3, GCM requires a full reinitialization of the context :(
EVP_CIPHER_CTX_reset(c)
else if c = nil then
begin
// allocate new encrypt/decrypt context
c := EVP_CIPHER_CTX_new;
Ctx[DoEncrypt] := c;
end
else
begin
// OpenSSL allows to reuse the previous Ctxt[], just setting the (new) IV
// -> this makes a huge performance benefit
// note: the latest API (i.e. EVP_CipherInit_ex on 1.1, EVP_CipherInit_ex2
// on 3.0) should be called to be able to reuse the context
EOpenSslCrypto.Check(Owner, method, EVP_CipherInit_ex2(
c, nil, nil, @Owner.IV, ord(DoEncrypt), nil));
exit;
end;
// full initialization of the context, with the proper key/IV and no padding
EOpenSslCrypto.Check(Owner, method,
EVP_CipherInit_ex2(
c, Cipher, @TAesAbstractOsl(Owner).fKey, @Owner.IV, ord(DoEncrypt), nil));
EOpenSslCrypto.Check(Owner, method,
EVP_CIPHER_CTX_set_padding(c, 0));
end;
procedure TAesOsl.UpdEvp(DoEncrypt: boolean; BufIn, BufOut: pointer;
Count: cardinal; KeepIV: boolean);
var
outl: integer;
c: PEVP_CIPHER_CTX;
begin
outl := 0;
c := Ctx[DoEncrypt];
EOpenSslCrypto.Check(Owner, 'UpdEvp',
EVP_CipherUpdate(c, BufOut, @outl, BufIn, Count));
if not KeepIV then
Owner.IV := PAesBlock(EVP_CIPHER_CTX_iv(c))^; // for fIVUpdated := true
// no need to call EVP_CipherFinal_ex() since we expect no padding
end;
{ ************** OpenSSL Cryptographic Pseudorandom Number Generator (CSPRNG) }
{ TAesPrngOsl }
class function TAesPrngOsl.IsAvailable: boolean;
begin
result := OpenSslIsAvailable;
end;
constructor TAesPrngOsl.Create;
begin
inherited Create;
EOpenSslCrypto.CheckAvailable(PClass(self)^, 'Create');
end;
procedure TAesPrngOsl.FillRandom(Buffer: pointer; Len: PtrInt);
begin
inc(fTotalBytes, Len);
EOpenSslCrypto.Check(RAND_bytes(Buffer, Len));
end;
var
MainAesPrngOsl: TAesPrngOsl;
class function TAesPrngOsl.Main: TAesPrngAbstract;
begin
result := MainAesPrngOsl;
if result <> nil then
exit;
EOpenSslCrypto.CheckAvailable(self, 'Main');
GlobalLock; // RegisterGlobalShutdownRelease() will use it anyway
try
if MainAesPrngOsl = nil then
MainAesPrngOsl := RegisterGlobalShutdownRelease(TAesPrngOsl.Create);
finally
GlobalUnLock;
end;
result := MainAesPrngOsl;
end;
{ ************** AES Cypher/Uncypher in various Modes }
{ TAesAbstractOsl }
procedure TAesAbstractOsl.AfterCreate;
var
nam: TShort15;
begin
AlgoName(nam); // always #0 terminated
fAes.Init(self, pointer(@nam[1]));
fIVUpdated := true; // fAes.UpdEvp() calls EVP_CIPHER_CTX_iv() to set IV
end;
destructor TAesAbstractOsl.Destroy;
begin
if HasOpenSsl then // avoid GPF at shutdown if some dangling instances
fAes.Done;
inherited Destroy;
end;
class function TAesAbstractOsl.IsAvailable: boolean;
begin
result := OpenSslIsAvailable;
end;
procedure TAesAbstractOsl.Encrypt(BufIn, BufOut: pointer; Count: cardinal);
begin
fAes.SetEvp({doencrypt=}true, 'Encrypt');
fAes.UpdEvp({doencrypt=}true, BufIn, BufOut, Count);
end;
procedure TAesAbstractOsl.Decrypt(BufIn, BufOut: pointer; Count: cardinal);
begin
fAes.SetEvp({doencrypt=}false, 'Decrypt');
fAes.UpdEvp({doencrypt=}false, BufIn, BufOut, Count);
end;
function TAesAbstractOsl.Clone: TAesAbstract;
begin
result := InternalCopy; // copy main properties
TAesAbstractOsl(result).fAes.Owner := result;
fAes.Clone(@TAesAbstractOsl(result).fAes); // efficient Ctx[] copy
end;
function TAesAbstractOsl.CloneEncryptDecrypt: TAesAbstract;
begin
result := self; // there is one Ctx[] for each direction
end;
{ TAesEcbOsl }
procedure TAesEcbOsl.AfterCreate;
begin
fAlgoMode := mEcb;
inherited AfterCreate;
end;
{ TAesCbcOsl }
procedure TAesCbcOsl.AfterCreate;
begin
fAlgoMode := mCbc;
inherited AfterCreate;
end;