-
-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathmormot.crypt.other.pas
More file actions
2415 lines (2246 loc) · 87.7 KB
/
Copy pathmormot.crypt.other.pas
File metadata and controls
2415 lines (2246 loc) · 87.7 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 Complementary Cryptographic Algorithms
// - 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.other;
{
*****************************************************************************
Deprecated or Seldom Used Cryptographic Features
- Deprecated MD4 and RC4 Support
- Deprecated Low-Level Memory Buffers Helper Functions
- Deprecated Weak AES/SHA Process
- BlowFish Encryption
- BCrypt Password-Hashing Function
- SCrypt Password-Hashing Function
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
classes,
sysutils,
mormot.core.base,
mormot.core.os,
mormot.core.buffers,
mormot.core.unicode,
mormot.core.text,
mormot.crypt.core;
{ **************** Deprecated MD4 and RC4 Support }
/// initialize a TMd5 instance to work with the legacy MD4 algorithm
// - will reuse the whole MD5 context but setup the MD4 transform function
// - MD4 is clearly deprecated, but available here for compatibility usage
procedure Md4Init(var Engine: TMd5);
/// direct MD4 hash calculation of some data
procedure Md4Buf(const Buffer; Len: cardinal; var Dig: TMd5Digest);
/// direct MD4 hash calculation of some data (string-encoded)
// - result is returned in lowercase hexadecimal format
function Md4(const s: RawByteString): RawUtf8;
type
/// implements RC4 encryption/decryption
// - this algorithm has known weaknesses, so should not be considered as
// cryptographic secure, but is available for other purposes
// - we defined a record instead of a class, to allow stack allocation and
// thread-safe reuse of one initialized instance
// - you can also restore and backup any previous state of the RC4 encryption
// by copying the whole TRC4 variable into another (stack-allocated) variable
{$ifdef USERECORDWITHMETHODS}
TRC4 = record
{$else}
TRC4 = object
{$endif USERECORDWITHMETHODS}
private
{$ifdef CPUINTEL}
state: array[byte] of PtrInt; // PtrInt=270MB/s byte=240MB/s on x86
{$else}
state: TByteToByte; // on ARM, keep the CPU cache usage low
{$endif CPUINTEL}
currI, currJ: PtrInt;
public
/// initialize the RC4 encryption/decryption
// - KeyLen is in bytes, and should be within 1..255 range
// - warning: aKey is an untyped constant, i.e. expects a raw set of memory
// bytes: do NOT use assign it with a string or a TBytes instance: you would
// use the pointer to the data as key
procedure Init(const aKey; aKeyLen: integer);
/// initialize RC4-drop[3072] encryption/decryption after SHA-3 hashing
// - will use SHAKE-128 generator in XOF mode to generate a 256 bytes key,
// then drop the first 3072 bytes from the RC4 stream
// - this initializer is much safer than plain Init, so should be considered
// for any use on RC4 for new projects - even if AES-NI is 2 times faster,
// and safer SHAKE-128 operates in XOF mode at a similar speed range
procedure InitSha3(const aKey; aKeyLen: integer);
/// drop the next Count bytes from the RC4 cypher state
// - may be used in Stream mode, or to initialize in RC4-drop[n] mode
procedure Drop(Count: cardinal);
/// perform the RC4 cypher encryption/decryption on a buffer
// - each call to this method shall be preceded with an Init() call
// - RC4 is a symmetrical algorithm: use this Encrypt() method
// for both encryption and decryption of any buffer
procedure Encrypt(const BufIn; var BufOut; Count: cardinal);
{$ifdef HASINLINE}inline;{$endif}
/// perform the RC4 cypher encryption/decryption on a buffer
// - each call to this method shall be preceded with an Init() call
// - RC4 is a symmetrical algorithm: use this EncryptBuffer() method
// for both encryption and decryption of any buffer
procedure EncryptBuffer(BufIn, BufOut: PByte; Count: cardinal);
end;
{ ****************** Deprecated Low-Level Memory Buffers Helper Functions }
{$ifndef PUREMORMOT2}
/// simple XOR encryption according to Cod - not Compression or Stream compatible
// - used in deprecated AESFull() for KeySize=32
// - Cod is used to derivate some pseudo-random content from internal constant
// tables, so encryption is weak but fast
procedure XorBlock(p: PIntegerArray; Count, Cod: integer);
/// simple XOR Cypher using Index (=Position in Dest Stream)
// - Compression not compatible with this function: should be applied after
// compress (e.g. as outStream for TAesWriteStream)
// - Stream compatible (with updated Index)
// - used in deprecated AES() and TAesWriteStream
// - Index is used to derivate some pseudo-random content from internal
// constant tables, so encryption is weak but fast
procedure XorOffset(P: PByteArray; Index, Count: PtrInt);
/// weak XOR Cypher changing by Count value
// - Compression compatible, since the XOR value is always the same, the
// compression rate will not change a lot
// - this encryption is very weak, so should be used only for basic
// obfuscation, not data protection
procedure XorConst(p: PIntegerArray; Count: integer);
{$endif PUREMORMOT2}
{ ****************** Deprecated Weak AES/SHA Process }
{$ifndef PUREMORMOT2}
type
{$A-}
/// internal header for storing our AES data with salt and CRC
// - memory size matches an TAesBlock on purpose, for direct encryption
// - TAesFull uses unsafe direct AES-ECB chain mode, so is considered deprecated
{$ifdef USERECORDWITHMETHODS}
TAesFullHeader = record
{$else}
TAesFullHeader = object
{$endif USERECORDWITHMETHODS}
public
/// Len before compression (if any)
OriginalLen,
/// Len before AES encoding
SourceLen,
/// Random Salt for better encryption
SomeSalt,
/// CRC from header
HeaderCheck: cardinal;
/// computes the Key checksum, using Adler32 algorithm
function Calc(const Key; KeySize: cardinal): cardinal;
end;
{$A+}
PAesFull = ^TAesFull;
/// AES and XOR encryption object for easy direct memory or stream access
// - calls internally TAes objet methods, and handle memory and streams for best speed
// - a TAesFullHeader is encrypted at the beginning, allowing fast Key validation,
// but the resulting stream is not compatible with raw TAes object
// - will use unsafe direct AES-ECB chain mode, so is considered deprecated
{$ifdef USERECORDWITHMETHODS}
TAesFull = record
{$else}
TAesFull = object
{$endif USERECORDWITHMETHODS}
public
/// header, stored at the beginning of struct -> 16-byte aligned
Head: TAesFullHeader;
/// this memory stream is used in case of EncodeDecode(outStream=bOut=nil)
// method call
outStreamCreated: TMemoryStream;
/// main method of AES or XOR cypher/uncypher
// - return out size, -1 if error on decoding (Key not correct)
// - valid KeySize: 0=nothing, 32=xor, 128,192,256=AES
// - if outStream is TMemoryStream -> auto-reserve space (no Realloc:)
// - for normal usage, you just have to Assign one In and one Out
// - if outStream AND bOut are both nil, an outStream is created via
// TMemoryStream.Create
// - if Encrypt -> OriginalLen can be used to store unCompressed Len
function EncodeDecode(const Key; KeySize, inLen: cardinal; Encrypt: boolean;
inStream, outStream: TStream; bIn, bOut: pointer; OriginalLen: cardinal = 0): integer;
end;
/// AES encryption stream (deprecated)
// - encrypt the Data on the fly, in a compatible way with AES() - last bytes
// are coded with XOR (not compatible with TAesFull format)
// - not optimized for small blocks -> ok if used AFTER TBZCompressor/TZipCompressor
// - warning: Write() will crypt Buffer memory in place -> use AFTER T*Compressor
// - will use unsafe direct AES-ECB chain mode, so is considered deprecated:
// consider TAesPkcs7Writer and TAesPkcs7Reader instead
TAesWriteStream = class(TStream)
public
Adler, // CRC from uncrypted compressed data - for Key check
DestSize: cardinal;
private
fDest: TStream;
fBuf: TAesBlock; // very small buffer for remainging 0..15 bytes
fBufCount: integer; // number of pending bytes (0..15) in Buf
fAes: TAes;
fNoCrypt: boolean; // if KeySize=0
public
/// initialize the AES encryption stream for an output stream (e.g.
// a TMemoryStream or a TFileStreamEx)
constructor Create(outStream: TStream; const Key; KeySize: cardinal);
/// finalize the AES encryption stream
// - internally call the Finish method
destructor Destroy; override;
/// read some data is not allowed -> this method will raise an exception on call
function Read(var Buffer; Count: Longint): Longint; override;
/// append some data to the outStream, after encryption
function Write(const Buffer; Count: Longint): Longint; override;
/// read some data is not allowed -> this method will raise an exception on call
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
/// write pending data
// - should always be called before closing the outStream (some data may
// still be in the internal buffers)
procedure Finish;
end;
/// direct Encrypt/Decrypt of data using the TAes class (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
procedure AES(const Key; KeySize: cardinal; buffer: pointer; Len: integer;
Encrypt: boolean); overload; deprecated;
/// direct Encrypt/Decrypt of data using the TAes class (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
procedure AES(const Key; KeySize: cardinal; bIn, bOut: pointer; Len: integer;
Encrypt: boolean); overload; deprecated;
/// direct Encrypt/Decrypt of data using the TAes class (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
function AES(const Key; KeySize: cardinal; const s: RawByteString;
Encrypt: boolean): RawByteString; overload; deprecated;
/// direct Encrypt/Decrypt of data using the TAes class (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
function AES(const Key; KeySize: cardinal; buffer: pointer; Len: cardinal;
Stream: TStream; Encrypt: boolean): boolean; overload; deprecated;
/// AES and XOR encryption using the TAesFull format (deprecated)
// - outStream will be larger/smaller than Len (full AES encrypted)
// - if KeySize is not in [128,192,256], will use a naive simple Xor Cypher
// - returns true if OK
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
function AESFull(const Key; KeySize: cardinal;
bIn: pointer; Len: integer; outStream: TStream; Encrypt: boolean;
OriginalLen: cardinal = 0): boolean; overload; deprecated;
/// AES and XOR encryption using the TAesFull format (deprecated)
// - bOut must be at least bIn+32/Encrypt bIn-16/Decrypt
// - if KeySize is not in [128,192,256], will use a naive simple Xor Cypher
// - returns outLength, -1 if error
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
function AESFull(const Key; KeySize: cardinal; bIn, bOut: pointer; Len: integer;
Encrypt: boolean; OriginalLen: cardinal = 0): integer; overload; deprecated;
/// AES and XOR decryption check using the TAesFull format (deprecated)
// - return true if the beginning of buff contains some data AESFull-encrypted
// with this Key
// - if not KeySize in [128,192,256], will always return true
// - will use unsafe direct AES-ECB chain mode, so is marked as deprecated
function AESFullKeyOK(const Key; KeySize: cardinal; buff: pointer): boolean; deprecated;
/// AES encryption using the TAes format with a supplied password (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode and weak direct SHA-256 (HMAC-256
// is preferred), so is marked as deprecated
procedure AESSHA256(Buffer: pointer; Len: integer; const Password: RawByteString;
Encrypt: boolean); overload; deprecated;
/// AES encryption using the TAes format with a supplied password (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode and weak direct SHA-256 (HMAC-256
// is preferred), so is marked as deprecated
procedure AESSHA256(bIn, bOut: pointer; Len: integer; const Password: RawByteString;
Encrypt: boolean); overload; deprecated;
/// AES encryption using the TAes format with a supplied password (deprecated)
// - last bytes (not part of 16 bytes blocks) are not crypted by AES, but with XOR
// - will use unsafe direct AES-ECB chain mode and weak direct SHA-256 (HMAC-256
// is preferred), so is marked as deprecated
function AESSHA256(const s, Password: RawByteString;
Encrypt: boolean): RawByteString; overload; deprecated;
/// AES encryption using the TAesFull format with a supplied password (deprecated)
// - outStream will be larger/smaller than Len: this is a full AES version with
// a triming TAesFullHeader at the beginning
// - will use unsafe direct AES-ECB chain mode and weak direct SHA-256 (HMAC-256
// is preferred), so is marked as deprecated
procedure AESSHA256Full(bIn: pointer; Len: integer; outStream: TStream;
const Password: RawByteString; Encrypt: boolean); overload; deprecated;
{$endif PUREMORMOT2}
{ **************** BlowFish Encryption }
type
/// BlowFish Subkeys
// - is 72 bytes, i.e. BCRYPT_MAXKEYLEN
TPBox = array[0..17] of cardinal;
/// BlowFish Subtitution Boxes
TSBox = array[0..1023] of cardinal;
/// the current BlowFish state
// - stored as PBox[] / SBox[] so that all blocks could be encrypted in order
TBlowFishState = record
/// BlowFish Subkeys
PBox: TPBox;
/// BlowFish Subtitution Boxes
SBox: TSBox;
end;
/// points to a TBlowFishState binary buffer
PBlowFishState = ^TBlowFishState;
const
BLOWFISH_SALTLEN = 16;
BLOWFISH_MAXKEYLEN = SizeOf(TPBox);
/// raw in-place encryption of one BlowFish 64-bit block
// - by design, this function is thread-safe, since TBlowFishState is untouched
procedure BlowFishEncrypt64(const s: TBlowFishState; block: PQWordRec);
/// BlowFish encryption using CTR block chain over the supplied IV
// - last len 1..7 bytes would be XORed from IV as per the CTR standard
// - by design, this function is thread-safe, since TBlowFishState is untouched
procedure BlowFishEncryptCtr(src, dest: PQWord; len: PtrUInt;
const state: TBlowFishState; iv: PQWord);
// published for testing purposes
procedure BlowFishCtrInc(iv: PQWord); {$ifndef ASMINTEL} inline; {$endif}
/// regular BlowFish key setup with a given salt and UTF-8 password
// - Salt is expected to be 16 bytes = 128-bit, e.g. from Random128()
// - Password will be passed to BlowFishPrepareKey() - so trimmed to 72 bytes -
// before calling the overloaded BlowFishKeySetup() binary function
procedure BlowFishKeySetup(var State: TBlowFishState;
Salt: PHash128Rec; const Password: RawUtf8); overload;
/// prepare a password into a binary key usable for BlowFishKeySetup()
// - Key is filled with the repeated Password and converted to big-endian
// - SaltBE returns a big-endian copy of Salt^; the caller's Salt^ buffer is
// not modified (previous versions byte-swapped Salt^ in place, which
// segfaulted on POSIX targets when the caller passed a pointer into
// rodata - e.g. @BLOWFISHCTR_DEFAULTSALT - and silently corrupted any
// writable typed-const salt on Delphi/Windows)
// - caller should FillZero(Key) once done
// - return the number of 64-bit blocks of the padded key
// - by design, Password will be truncated to 72 bytes (BLOWFISH_MAXKEYLEN)
function BlowFishPrepareKey(const Password: RawUtf8; Salt: PHash128Rec;
out SaltBE: THash128Rec; out Key: RawByteString): PtrInt;
/// raw BlowFish key setup with binary input parameters
// - salt is expected to be 16 bytes = 128-bit
// - key is expected to be already prepared with ending #0 and in 64-bit chunks
// - consider BCryptExpensiveKeySetup() for a safer (and slower) initialization
procedure BlowFishKeySetup(var State: TBlowFishState;
Salt, Key: PQwordArray; KeyBlocks: PtrUInt); overload;
/// finalize a given BlowFish key state in memory
procedure BlowFishKeyClear(var State: TBlowFishState);
type
/// a convenient way to use BlowFish-CTR encoding/decoding
TBlowFishCtr = class
protected
fIV: QWord;
fState: PBlowFishState;
public
/// setup the BlowFish-CTR context for cypher
// - by design, BlowFish has its own safe password-hashing algorithm: no need
// to use a cryptographic hash first (unless the password is > 72 bytes)
// - with default Cost = 0, will use regular BlowFishKeySetup()
// - Cost in [1..31] uses safer (and much slower) BCryptExpensiveKeySetup()
// - if no Salt is supplied, a fixed value (from this unit) will be used
// - in comparison e.g. with AES, key setup can be (very) slow: don't use
// this class and algorithm for a short transient message
constructor Create(const Password: RawByteString; Cost: byte = 0;
Salt: PHash128Rec = nil); reintroduce;
/// finalize this instance
destructor Destroy; override;
/// perform the actual encoding/decoding on binary buffers
// - CTR is a reverse algorithm: apply once to cipher, and again to decipher
// - Count may not be an exact multiple of 64-bit - will trim the IV bytes
// - will update the internal IV - so you can call this method several times
// but this method won't be thread-safe
procedure EncryptBuffer(BufIn, BufOut: pointer; Count: cardinal);
/// perform the actual encoding on a RawByteString with proper CTR padding
// - if IVAtBeginning is TRUE, a random 64-bit Initialization Vector will be
// generated and stored at the beginning of the output buffer - this will
// also make this method thread-safe
// - if IVAtBeginning is FALSE, internal IV will be used (not thread-safe)
function Encrypt(const Input: RawByteString;
IVAtBeginning: boolean = false): RawByteString;
/// perform the actual decoding on a RawByteString with proper CTR padding
// - if IVAtBeginning is TRUE, a random 64-bit Initialization Vector is
// expected to be stored at the beginning of the output buffer - this
// will also make this method thread-safe
// - if IVAtBeginning is FALSE, internal IV will be used (not thread-safe)
function Decrypt(const Input: RawByteString;
IVAtBeginning: boolean = false): RawByteString;
/// access to the current 64-bit IV state
property IV: QWord
read fIV write fIV;
/// raw access to the BlowFish expanded internal key context
// - could be used e.g. for thread-safe process of the current secret key
// using direct BlowFishEncryptCtr() call
property State: PBlowFishState
read fState;
end;
{ **************** BCrypt Password-Hashing Function }
const
BCRYPT_MAXKEYLEN = BLOWFISH_MAXKEYLEN;
BCRYPT_SALTLEN = BLOWFISH_SALTLEN;
/// BCrypt password hashing function as used on BSD systems
// - this adaptative algorithm has no known weaknesses, and there are reports
// that the more recent Argon2 is weaker (and less proven) for practical timing,
// and SCrypt requires N>=2^14 to be stronger (i.e. at least 16MB), so BCrypt
// seems still the best solution for server-side password hashing
// - Cost should be in range 4..31 for 2^Cost rounds (default value is 12, and
// takes 180ms on my computer)
// - Salt='' would generate one - or should be exactly 22 characters (16 bytes)
// - PreSha256 would HMAC-SHA-256 the password (returning $bcrypt-sha256$) to
// circumvent the initial password length limitation of 72 chars
// - assigned to mormot.crypt.core.pas BCrypt() redirection by this unit
// - returns e.g. '$2b$<cost>$<salt><checksum>' for the regular BSD format or
// '$bcrypt-sha256$v=2,t=2b,r=<cost>$<salt'$ for the passlib extended format
function BCryptHash(const Password: RawUtf8; const Salt: RawUtf8 = '';
Cost: byte = 12; HashPos: PInteger = nil; PreSha256: boolean = false): RawUtf8;
/// prepare a BlockFish encryption with a given Salt, UTF-8 Password and Cost
// - Password is process using the BCrypt "Expensive Key Setup" algorithm
// - Cost should be in range 4..31
// - Salt is expected to be 16 bytes = 128-bit, e.g. from Random128()
procedure BCryptExpensiveKeySetup(var State: TBlowFishState;
Cost: byte; Salt: PHash128Rec; const Password: RawUtf8);
{ **************** SCrypt Password-Hashing Function }
{$ifndef ASMSSE2}
/// apply in-place Salsa20/8 transformation over a 64 bytes buffer
// - only used in pure pascal mode, when NOASMBLOCK/HASNOSSE2 are defined
procedure Salsa20x8(B: PCardinalArray);
{$endif ASMSSE2}
/// low-level SCrypt hash computation using our pure pascal code
// - the tuned SSE2 code of this unit is faster than mormot.lib.openssl11:
// $ on Win32: RawSCrypt in 101ms, OpenSslScrypt in 157ms
// $ on Win64: RawSCrypt in 92ms, OpenSslScrypt in 124ms
// $ on Linux x64: RawSCrypt in 74ms, OpenSslScrypt in 103ms
// - assigned to mormot.crypt.core.pas SCrypt() redirection by this unit
// - for password storage and interactive login, consider SCryptHash() from
// mormot.crypt.secure.pas with N=65536=2^16, R=8, P=2 (148ms and 64MB of RAM)
// - for local key derivation (e.g. file encryption) consider using this
// function directly with e.g. N=1048576=2^20, R=8, P=1 (1.23s and 1GB) to
// compute the binary encryption key
function RawSCrypt(const Password: RawUtf8; const Salt: RawByteString;
N, R, P, DestLen: PtrUInt): RawByteString;
/// compute how much memory the SCrypt() function will allocate
// - could be used to tune the parameters (N, R, P) somewhat obfuscated meaning
// - return e.g. 16MB for SCrypt(16384, 8, 1) and 64MB for SCrypt(65536, 8, 1),
// i.e. equals roughtly N * R * 128 with some more bytes depending on P
// - SCrypt(16384, 8, 1) are the recommended minimal parameters value to have
// benefits against BCrypt() - but still consuming 16MB instead of 4KB so may
// not be ideal for password storage on server side, but fine for a client-side
// one-time key derivation function to unlock a resource
// - TL&WR: use N=65536=2^16, R=8, P=2 for safe interactive login (148ms and
// 64MB of RAM) or N=1048576=2^20, R=8, P=1 for file encryption (1.23s and 1GB)
function SCryptMemoryUse(N, R, P: QWord): QWord;
implementation
{ **************** Deprecated MD4 and RC4 Support }
{$ifndef FPC} // this operation is an intrinsic with the FPC compiler
function RolDWord(value: cardinal; count: integer): cardinal;
{$ifdef HASINLINE} inline; {$endif}
begin
result := (value shl count) or (value shr (32 - count));
end;
{$endif FPC}
procedure MD4Transform(var buf: TMd5Buf; const in_: TMd5In);
var
a, b, c, d, e: cardinal;
begin // fast enough unrolled code - especially with FPC RolDWord() intrinsic
a := buf[0];
b := buf[1];
c := buf[2];
d := buf[3];
a := RolDWord(a + (d xor (b and (c xor d))) + in_[ 0], 3);
d := RolDWord(d + (c xor (a and (b xor c))) + in_[ 1], 7);
c := RolDWord(c + (b xor (d and (a xor b))) + in_[ 2], 11);
b := RolDWord(b + (a xor (c and (d xor a))) + in_[ 3], 19);
a := RolDWord(a + (d xor (b and (c xor d))) + in_[ 4], 3);
d := RolDWord(d + (c xor (a and (b xor c))) + in_[ 5], 7);
c := RolDWord(c + (b xor (d and (a xor b))) + in_[ 6], 11);
b := RolDWord(b + (a xor (c and (d xor a))) + in_[ 7], 19);
a := RolDWord(a + (d xor (b and (c xor d))) + in_[ 8], 3);
d := RolDWord(d + (c xor (a and (b xor c))) + in_[ 9], 7);
c := RolDWord(c + (b xor (d and (a xor b))) + in_[10], 11);
b := RolDWord(b + (a xor (c and (d xor a))) + in_[11], 19);
a := RolDWord(a + (d xor (b and (c xor d))) + in_[12], 3);
d := RolDWord(d + (c xor (a and (b xor c))) + in_[13], 7);
c := RolDWord(c + (b xor (d and (a xor b))) + in_[14], 11);
b := RolDWord(b + (a xor (c and (d xor a))) + in_[15], 19);
e := $5a827999;
a := RolDWord(a + ((b and c) or (b and d) or (c and d)) + in_[ 0] + e, 3);
d := RolDWord(d + ((a and b) or (a and c) or (b and c)) + in_[ 4] + e, 5);
c := RolDWord(c + ((d and a) or (d and b) or (a and b)) + in_[ 8] + e, 9);
b := RolDWord(b + ((c and d) or (c and a) or (d and a)) + in_[12] + e, 13);
a := RolDWord(a + ((b and c) or (b and d) or (c and d)) + in_[ 1] + e, 3);
d := RolDWord(d + ((a and b) or (a and c) or (b and c)) + in_[ 5] + e, 5);
c := RolDWord(c + ((d and a) or (d and b) or (a and b)) + in_[ 9] + e, 9);
b := RolDWord(b + ((c and d) or (c and a) or (d and a)) + in_[13] + e, 13);
a := RolDWord(a + ((b and c) or (b and d) or (c and d)) + in_[ 2] + e, 3);
d := RolDWord(d + ((a and b) or (a and c) or (b and c)) + in_[ 6] + e, 5);
c := RolDWord(c + ((d and a) or (d and b) or (a and b)) + in_[10] + e, 9);
b := RolDWord(b + ((c and d) or (c and a) or (d and a)) + in_[14] + e, 13);
a := RolDWord(a + ((b and c) or (b and d) or (c and d)) + in_[ 3] + e, 3);
d := RolDWord(d + ((a and b) or (a and c) or (b and c)) + in_[ 7] + e, 5);
c := RolDWord(c + ((d and a) or (d and b) or (a and b)) + in_[11] + e, 9);
b := RolDWord(b + ((c and d) or (c and a) or (d and a)) + in_[15] + e, 13);
e := $6ed9eba1;
a := RolDWord(a + (b xor c xor d) + in_[ 0] + e, 3);
d := RolDWord(d + (a xor b xor c) + in_[ 8] + e, 9);
c := RolDWord(c + (d xor a xor b) + in_[ 4] + e, 11);
b := RolDWord(b + (c xor d xor a) + in_[12] + e, 15);
a := RolDWord(a + (b xor c xor d) + in_[ 2] + e, 3);
d := RolDWord(d + (a xor b xor c) + in_[10] + e, 9);
c := RolDWord(c + (d xor a xor b) + in_[ 6] + e, 11);
b := RolDWord(b + (c xor d xor a) + in_[14] + e, 15);
a := RolDWord(a + (b xor c xor d) + in_[ 1] + e, 3);
d := RolDWord(d + (a xor b xor c) + in_[ 9] + e, 9);
c := RolDWord(c + (d xor a xor b) + in_[ 5] + e, 11);
b := RolDWord(b + (c xor d xor a) + in_[13] + e, 15);
a := RolDWord(a + (b xor c xor d) + in_[ 3] + e, 3);
d := RolDWord(d + (a xor b xor c) + in_[11] + e, 9);
c := RolDWord(c + (d xor a xor b) + in_[ 7] + e, 11);
b := RolDWord(b + (c xor d xor a) + in_[15] + e, 15);
inc(buf[0], a);
inc(buf[1], b);
inc(buf[2], c);
inc(buf[3], d);
end;
procedure Md4Init(var Engine: TMd5);
begin
Engine.Init(@MD4Transform);
end;
procedure Md4Buf(const Buffer; Len: cardinal; var Dig: TMd5Digest);
var
md: TMd5;
begin
Md4Init(md);
md.Update(Buffer, Len);
md.Final(Dig);
end;
function Md4(const s: RawByteString): RawUtf8;
var
dig: TMd5Digest;
begin
Md4Buf(pointer(s)^, Length(s), dig);
BinToHexLower(@dig, SizeOf(dig), result);
FillZero(dig);
end;
{ TRC4 }
procedure TRC4.Init(const aKey; aKeyLen: integer);
var
i, k: integer;
j, tmp: PtrInt;
begin
if aKeyLen <= 0 then
ESynCrypto.RaiseUtf8('TRC4.Init(invalid aKeyLen=%)', [aKeyLen]);
dec(aKeyLen);
for i := 0 to high(state) do
state[i] := i;
j := 0;
k := 0;
for i := 0 to high(state) do
begin
j := (j + state[i] + TByteArray(aKey)[k]) and $ff;
tmp := state[i];
state[i] := state[j];
state[j] := tmp;
if k >= aKeyLen then // avoid slow mod operation within loop
k := 0
else
inc(k);
end;
currI := 0;
currJ := 0;
end;
procedure TRC4.InitSha3(const aKey; aKeyLen: integer);
var
sha: TSha3;
dig: TByteToByte; // max RC4 state size is 256 bytes
begin
sha.Full(SHAKE_128, @aKey, aKeyLen, @dig, SizeOf(dig) shl 3); // XOF mode
Init(dig, SizeOf(dig));
FillCharFast(dig, SizeOf(dig), 0);
Drop(3072); // 3KB warmup
end;
procedure TRC4.EncryptBuffer(BufIn, BufOut: PByte; Count: cardinal);
var
i, j, ki, kj: PtrInt;
by4: array[0..3] of byte;
begin
i := currI;
j := currJ;
while Count > 3 do
begin
dec(Count, 4);
i := (i + 1) and $ff;
ki := State[i];
j := (j + ki) and $ff;
kj := (ki + State[j]) and $ff;
State[i] := State[j];
i := (i + 1) and $ff;
State[j] := ki;
ki := State[i];
by4[0] := State[kj];
j := (j + ki) and $ff;
kj := (ki + State[j]) and $ff;
State[i] := State[j];
i := (i + 1) and $ff;
State[j] := ki;
by4[1] := State[kj];
ki := State[i];
j := (j + ki) and $ff;
kj := (ki + State[j]) and $ff;
State[i] := State[j];
i := (i + 1) and $ff;
State[j] := ki;
by4[2] := State[kj];
ki := State[i];
j := (j + ki) and $ff;
kj := (ki + State[j]) and $ff;
State[i] := State[j];
State[j] := ki;
by4[3] := State[kj];
PCardinal(BufOut)^ := PCardinal(BufIn)^ xor cardinal(by4);
inc(BufIn, 4);
inc(BufOut, 4);
end;
while Count > 0 do
begin
dec(Count);
i := (i + 1) and $ff;
ki := State[i];
j := (j + ki) and $ff;
kj := (ki + State[j]) and $ff;
State[i] := State[j];
State[j] := ki;
BufOut^ := BufIn^ xor State[kj];
inc(BufIn);
inc(BufOut);
end;
currI := i;
currJ := j;
end;
procedure TRC4.Encrypt(const BufIn; var BufOut; Count: cardinal);
begin
EncryptBuffer(@BufIn, @BufOut, Count);
end;
procedure TRC4.Drop(Count: cardinal);
var
i, j, ki: PtrInt;
begin
i := currI;
j := currJ;
while Count > 0 do
begin
dec(Count);
i := (i + 1) and $ff;
ki := state[i];
j := (j + ki) and $ff;
state[i] := state[j];
state[j] := ki;
end;
currI := i;
currJ := j;
end;
{ ****************** Deprecated Low-Level Memory Buffers Helper Functions }
{$ifndef PUREMORMOT2}
procedure XorBlock(P: PIntegerArray; Count, Cod: integer);
// very fast Xor() according to Cod - not Compression or Stream compatible
var
i: integer;
tab: PIntegerArray;
begin
tab := AesTables; // = TD0[]
for i := 1 to Count shr 4 do
begin
// proceed through 16 bytes blocs
Cod := (Cod shl 11) xor tab[Cod shr 21]; // shr 21 -> 8*[byte] of cardinal
P^[0] := P^[0] xor Cod;
P^[1] := P^[1] xor Cod;
P^[2] := P^[2] xor Cod;
P^[3] := P^[3] xor Cod;
inc(PByte(P), 16);
end;
Cod := (Cod shl 11) xor tab[Cod shr 21];
for i := 1 to (Count and AesBlockMod) shr 2 do
begin
// last 4 bytes blocs
P^[0] := P^[0] xor Cod;
inc(PByte(P), 4);
end;
for i := 1 to Count and 3 do
begin
PByte(P)^ := PByte(P)^ xor byte(Cod);
inc(PByte(P));
end;
end;
procedure XorOffset(P: PByteArray; Index, Count: PtrInt);
// XorOffset: fast and simple Cypher using Index (= Position in Dest Stream):
// Compression not OK -> apply after compress
var
Len: PtrInt;
tab: PByteArray; // 2^13=$2000=8192 bytes of XOR tables ;)
begin
tab := AesTables; // = TD0[]
if Count > 0 then
repeat
Index := Index and $1FFF;
Len := $2000 - Index;
if Len > Count then
Len := Count;
XorMemory(P, @tab[Index], Len);
inc(P, Len);
inc(Index, Len);
dec(Count, Len);
until Count = 0;
end;
procedure XorConst(P: PIntegerArray; Count: integer);
// XorConst: fast Cypher changing by Count value (weak cypher but compression OK)
var
i: PtrInt;
Code: integer;
begin
// 1 to 3 bytes may stay unencrypted: not relevant
Code := PIntegerArray(AesTables)[Count and $3FF];
for i := 1 to (Count shr 4) do
begin
P^[0] := P^[0] xor Code;
P^[1] := P^[1] xor Code;
P^[2] := P^[2] xor Code;
P^[3] := P^[3] xor Code;
inc(PByte(P), 16);
end;
for i := 0 to ((Count and AesBlockMod) shr 2) - 1 do // last 4 bytes blocs
P^[i] := P^[i] xor Code;
end;
{$endif PUREMORMOT2}
{ ****************** Deprecated Weak AES/SHA Process }
{$ifndef PUREMORMOT2}
procedure AES(const Key; KeySize: cardinal; buffer: pointer; Len: integer;
Encrypt: boolean);
begin
{%H-}AES(Key, KeySize, buffer, buffer, Len, Encrypt);
end;
procedure AES(const Key; KeySize: cardinal; bIn, bOut: pointer; Len: integer;
Encrypt: boolean);
var
n: integer;
pi, po: PAesBlock;
aes: TAes;
begin
if (bIn = nil) or
(bOut = nil) then
exit;
// 1. Init
n := Len shr AesBlockShift;
if n < 0 then
exit;
aes.InitOnStack;
if n > 0 then
if (KeySize > 4) and
not aes.DoInit(Key, KeySize, Encrypt) then
// if error in KeySize, use default fast XorOffset()
KeySize := 4;
if KeySize = 0 then
begin
// KeySize=0 -> no encryption -> direct copy
MoveFast(bIn^, bOut^, Len);
exit;
end;
if n < 1 then
begin
// too small for AES -> XorOffset() remaining 0..15 bytes
MoveFast(bIn^, bOut^, Len);
XorOffset(bOut, 0, Len);
exit;
end;
// 2. All full blocks, with AES
aes.DoBlocks(bIn, bOut, pi, po, n, Encrypt);
// 3. Last block, just XORed from Key
// assert(KeySize div 8 >= AesBlockSize);
n := cardinal(Len) and AesBlockMod;
MoveFast(pi^, po^, n); // pi=po is tested in MoveFast()
XorOffset(pointer(po), Len - n, n);
aes.Done;
end;
const
TmpSize = 65536;
// Tmp buffer for AESFull -> Xor Crypt is TmpSize-dependent / use XorBlock()
TmpSizeBlock = TmpSize shr AesBlockShift;
type
TTmp = array[0..TmpSizeBlock - 1] of TAesBlock;
function AES(const Key; KeySize: cardinal; const s: RawByteString;
Encrypt: boolean): RawByteString;
begin
FastNewRawByteString(result, length(s));
if s <> '' then
{%H-}AES(Key, KeySize, pointer(s), pointer(result), length(s), Encrypt);
end;
function AES(const Key; KeySize: cardinal; buffer: pointer; Len: cardinal;
Stream: TStream; Encrypt: boolean): boolean;
var
buf: pointer;
last, b, n, i: cardinal;
aes: TAes;
begin
result := false;
if buffer = nil then
exit;
aes.InitOnStack;
if (KeySize > 4) and
not aes.DoInit(Key, KeySize, Encrypt) then
// if error in KeySize, use default fast XorOffset()
KeySize := 4;
if KeySize = 0 then
begin
// no aes -> direct write to dest Stream
Stream.WriteBuffer(buffer^, Len);
result := true;
exit;
end;
GetMem(buf, TmpSize);
try
last := Len and AesBlockMod;
n := Len - last;
i := 0;
while n > 0 do
begin
// aes/uncrypt all AesBlocks
if n > TmpSize then
b := TmpSize
else
b := n;
assert(b and AesBlockMod = 0);
if KeySize = 4 then
begin
MoveFast(buffer^, buf^, b);
XorOffset(pointer(buf), i, b);
inc(i, b);
end
else
aes.DoBlocks(buffer, buf, b shr AesBlockShift, Encrypt);
Stream.WriteBuffer(buf^, b);
inc(PByte(buffer), b);
dec(n, b);
end;
assert((KeySize > 4) or (i = Len - last));
if last > 0 then
begin
// aes/uncrypt (Xor) last 0..15 bytes
MoveFast(buffer^, buf^, last);
XorOffset(pointer(buf), Len - last, last);
Stream.WriteBuffer(buf^, last);
end;
result := true;
finally
FreeMem(buf);
end;
end;
function KeyFrom(const Key; KeySize: cardinal): cardinal;
begin
case KeySize div 8 of
0:
result := 0;
1:
result := PByte(@Key)^;
2, 3:
result := PWord(@Key)^;
else
result := PInteger(@Key)^;
end;
end;
function TAesFullHeader.Calc(const Key; KeySize: cardinal): cardinal;
var
tab: PCardinalArray;
begin
tab := AesTables;
result := adler32(KeySize, @Key, KeySize shr 3) xor
tab[$400 + OriginalLen and $ff] xor // = TE0[]
tab[$500 + SourceLen and $ff] xor // = TE1[]
tab[SomeSalt and $7ff]; // = TD0[]
end;
function TAesFull.EncodeDecode(const Key; KeySize, inLen: cardinal;
Encrypt: boolean; inStream, outStream: TStream; bIn, bOut: pointer;
OriginalLen: cardinal): integer;
var
tmp: ^TTmp;
pi, po: PAesBlock;
aes: TAes;
blocks, cod: cardinal;
procedure Read(tmp: pointer; ByteCount: cardinal);
begin
if pi = nil then
inStream.ReadBuffer(tmp^, ByteCount)
else
begin
MoveFast(pi^, tmp^, ByteCount);
inc(PByte(pi), ByteCount);
end;
end;
procedure Write(tmp: pointer; ByteCount: cardinal);
begin
if po = nil then
outStream.WriteBuffer(tmp^, ByteCount)
else
begin
MoveFast(tmp^, po^, ByteCount);
inc(PByte(po), ByteCount);
end;
end;
procedure SetOutLen(Len: cardinal);
var
P: cardinal;
begin
result := Len; // global EncodeDecode() result
if outStream <> nil then
begin
if outStream.InheritsFrom(TMemoryStream) then
begin
P := outStream.Position;
outStream.Size := P + Len; // auto-reserve space
outStream.Seek(P + Len, soBeginning);
bOut := PAnsiChar(TMemoryStream(outStream).Memory) + P;
po := bOut;
outStream := nil; // OutStream is slower and use no thread
end;
end
else if bOut = nil then
begin
outStreamCreated := TMemoryStream.Create;
outStreamCreated.Size := Len; // auto-reserve space (no Realloc:)
bOut := outStreamCreated.Memory;
po := bOut; // OutStream is slower and use no thread
end;
if KeySize = 0 then
exit; // no tmp to be allocated on direct copy