forked from JackTrapper/scrypt-for-delphi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSCrypt.pas
3346 lines (2783 loc) · 106 KB
/
SCrypt.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
unit SCrypt;
(*
Sample Usage
============
//Hash a password
hash := TSCrypt.HashPassword('correct horse battery staple');
//Check if password matches previous hash
isValid := TScrypt.CheckPassword('correct horse battery staple', hash);
//Derive an encryption key from a password
secretKey := TScrypt.GetBytes('correct horse battery staple', 'seasalt', 16); //returns 16 bytes (128 bits)
secretKey := TScrypt.GetBytes('correct horse battery staple', 'seasalt', {r=}1, {N=}128}, {p=}8, 32); //returns 32 bytes (256 bits)
Remarks
=======
scrypt is a key-derivation function.
Key derivation functions are used to derive an encryption key from a password.
To generate 16 bytes (128 bits) of key material, with automatically determined parameters, use:
secretKey := TScrypt.GetBytes('correct horse battery staple', 'seasalt', 16); //returns 16 bytes (128 bits)
If you know what values of the scrypt N (CostFactor), r (block size), and p (parallelization factor) parameters you want,
you can specify them:
secretKey := TScrypt.GetBytes('correct horse battery staple', 'seasalt', {N=}14, {r=}8, {p=}1, 32); //returns 32 bytes (256 bits)
where
BlockSize (r) = 8
CostFactor (N) = 14 (i.e. 2^14 = 16,384 iterations)
ParallelizationFactor (p) = 1
DesiredBytes = 32 (256 bits)
Otherwise scrypt does a speed/memory test to determine the most appropriate parameters.
Password Hashing
================
SCrypt has also been used as password hashing algorithm.
In order to make password storage easier, we generate the salt and store it with the returned string.
This is similar to what OpenBSD has done with BCrypt.
The downside is that there is no standard format out there for SCrypt representation of password hashes.
hash := TSCrypt.HashPassword('correct horse battery staple');
will return string in the format of:
$s0$NNNNrrpp$salt$key
s0 - version 0 of the format with 128-bit salt and 256-bit derived key
params - 32-bit hex integer containing log2(N) (16 bits), r (8 bits), and p (8 bits)
salt - 24 base64-encoded characters of salt (128 bits ==> 16 bytes ==> 24 characters)
key - 44 base64-encoded characters derived key (256 bits ==> 32 bytes ==> 44 characters)
Example for password of "secret":
$s0$e0801$epIxT/h6HbbwHaehFnh/bw==$7H0vsXlY8UxxyW/BWx/9GuY7jEvGjT71GFd6O4SZND0=
CostFactor = 0xE0 = 14 ==> N = 2^14 = 16,384
r = 0x08 = 8
p = 0x01 = 1
salt = epIxT/h6HbbwHaehFnh/bw==
key = 7H0vsXlY8UxxyW/BWx/9GuY7jEvGjT71GFd6O4SZND0=
Version History
===============
Version 1.5 20160603
- Change: CheckPassword to take a boolean out parameter "PasswordRehashNeeded". PasswordRehashNeeded will contain true
if you should call HashPassword again while you have the user's password handy.
If computing power can now compute the hash in less than 250ms, it's time to use rehash te password.
Or if the scrypt version or hash string format has changed, and we want you to use HashPassword to get a new format.
- Added: HashPassword (the version where you let scrypt determine the parameters) will now do a mini benchmark
(like Bcrypt for Delphi and canonical tarsnap scrypt does). The benchmark will try to ensure that scrypt
runs in no less than 250ms (ideally 500ms). But under no circumstances will the benchmark drop below the
default N=14,r=8,p=1. If the benchmark says that will take over 500ms to run, then that's the way it will be.
The benchmark will only ever *increase* runtime over the default, never decrease it.
Version 1.4 20160528
- Switched password hashing Base64 to use standard Base64 rather than OpenBSD's custom Base64 that BCrypt uses
- Hashing now compatible with wg/scrypt (added test to match their documented example)
- Standard base64 hashing keeps trailing == padding (BCrypt's custom Base64 stripped it)
- Removed unused variant of Salsa20 - the in-place is the only one used
- tried to make scrypt work on non-MSWINDOWS (e.g. use of ComObj and ActiveX for bestcrypt and capi)
- moved CreateObject to public rather than protected (no longer need cracker class to get at it).
It exists so people can use it; but i'm not sure how i feel about it being truly public.
- Fixed range-check bug when passing empty salt to PBKDF2
Version 1.3 20160509
- made compatible with Delphi 5/7
- Change some array indexing to use pointer offsets instead; the unnecessary bounds checking was getting confused
- Refactored core method to reinforce the idea that Scrypt is just simply PBKDF2 (with some fancy salt)
Version 1.2 20150510
- Use Cryptography Next Generation (Cng) API for SHA256 (requires Windows Vista or later)
- Will still fallback to SHA256 CryptoApi CSP (Windows 2000) when on Windows platform
- still falls back to internal PurePascal implementation if not WINDOWS
- Changed the strings to pass to TScrypt.GetHashAlgorithm
- Calling TScrypt.GetHashAlgoritm with "SHA1" or "SHA256" will now choose the best algorithm implementation
- Pass "SHA1PurePascal" or "SHA256PurePascal" to specifically get the pure pascal versions
- FIX: HashPassword overload that takes custom cost parameters was using stack garbage for salt
Version 1.1 20150415
- Support for actually verifying a password hash
- 43% faster due to optimizations in XorBlock and Salsa20
- TODO: Do the same thing canonical scrypt.c does, and do a benchmark before generation to determine parameters.
Version 1.0 20150408
- Inital release. Public domain. Ian Boyd.
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any means.
For more information, please refer to <http://unlicense.org>
Benchmarks
==========
20150412 Delphi XE6, Release, 32-bit, Intel i5-2500
| N | r=1 | r=2 | r=3 | r=4 | r=5 | r=6 | r=7 | r=8 | r=9 | r=10 | r=11 | r=12 | r=13 | r=14 | r=15 | r=16 |
|----|------|--------|--------|--------|--------|--------|---------|---------|---------|---------|--------|--------|---------|---------|---------|---------|
| 1 | 0.2 | 0.2 | 0.2 | 0.2 | 0.2 | 0.2 | 0.3 | 0.3 | 0.3 | 0.3 | 0.4 | 0.4 | 0.4 | 0.5 | 1.3 | 1.2 |
| 2 | 0.2 | 0.2 | 0.2 | 0.2 | 0.2 | 0.3 | 0.3 | 0.3 | 0.3 | 0.4 | 0.4 | 0.4 | 0.4 | 0.5 | 0.5 | 0.5 |
| 3 | 0.2 | 0.2 | 0.2 | 0.2 | 0.2 | 0.3 | 0.3 | 0.3 | 0.4 | 0.4 | 0.4 | 0.4 | 0.5 | 0.5 | 0.5 | 0.5 |
| 4 | 0.2 | 0.2 | 0.2 | 0.3 | 0.3 | 1.1 | 0.4 | 1.3 | 0.6 | 0.7 | 0.6 | 0.6 | 0.7 | 0.7 | 0.7 | 0.8 |
| 5 | 0.2 | 0.2 | 0.3 | 0.4 | 0.4 | 0.4 | 0.5 | 0.6 | 0.6 | 0.7 | 0.8 | 0.8 | 0.9 | 0.9 | 1.0 | 1.0 |
| 6 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.9 | 0.9 | 1.0 | 1.1 | 1.2 | 1.3 | 1.4 | 1.4 | 1.6 | 1.8 |
| 7 | 0.4 | 0.5 | 0.8 | 0.9 | 1.1 | 1.2 | 1.4 | 1.8 | 1.8 | 2.0 | 2.2 | 2.3 | 2.5 | 2.8 | 2.8 | 3.1 |
| 8 | 0.6 | 1.0 | 1.3 | 1.6 | 2.0 | 2.4 | 2.7 | 3.1 | 3.5 | 3.8 | 4.2 | 7.2 | 4.5 | 4.8 | 5.5 | 6.9 |
| 9 | 1.1 | 1.7 | 3.1 | 6.0 | 6.2 | 4.3 | 5.2 | 5.6 | 6.3 | 6.9 | 9.5 | 11.2 | 11.5 | 9.4 | 11.8 | 10.8 |
| 10 | 2.0 | 3.2 | 4.8 | 6.2 | 7.8 | 8.5 | 9.6 | 11.3 | 15.7 | 18.4 | 21.1 | 21.0 | 20.9 | 20.1 | 22.9 | 23.1 |
| 11 | 4.0 | 6.6 | 9.1 | 18.8 | 15.4 | 16.9 | 19.5 | 27.4 | 32.6 | 27.5 | 29.9 | 34.4 | 38.1 | 45.7 | 41.6 | 48.1 |
| 12 | 7.6 | 14.0 | 19.9 | 25.3 | 30.0 | 34.1 | 41.6 | 49.4 | 61.9 | 58.8 | 63.5 | 73.6 | 74.6 | 83.0 | 86.4 | 92.5 |
| 13 | 15.3 | 27.4 | 44.4 | 52.3 | 66.7 | 80.7 | 81.3 | 97.1 | 112.3 | 126.1 | 129.1 | 143.8 | 159.3 | 164.4 | 171.1 | 175.2 |
| 14 | 37.3 | 51.3 | 75.4 | 101.9 | 130.5 | 149.5 | 184.1 | 195.7 | 219.6 | 258.3 | 250.7 | 280.6 | 305.9 | 324.9 | 360.2 | 370.2 |
| 15 | 70.3 | 118.3 | 158.4 | 196.5 | 258.6 | 315.7 | 355.7 | 393.2 | 472.8 | 501.7 | 540.8 | 619.8 | 662.0 | 685.8 | 729.9 | 791.3 |
| 16 | #N/A | 229.2 | 305.8 | 430.2 | 521.8 | 624.7 | 700.9 | 823.3 | 909.2 | 1013.5 | 1056.3 | 1190.5 | 1318.4 | 1412.5 | 1501.5 | 1583.2 |
| 17 | #N/A | 505.1 | 691.5 | 845.0 | 1010.6 | 1243.0 | 1455.5 | 1602.0 | 1798.4 | 2031.1 | 2233.9 | 2436.9 | 2698.8 | 2856.4 | 3043.1 | 3240.8 |
| 18 | #N/A | 1003.6 | 1415.8 | 1797.0 | 2218.8 | 2597.6 | 2995.2 | 3375.1 | 3749.6 | 4074.9 | 4360.2 | 4655.6 | 5746.6 | 5987.7 | 5804.7 | 6181.3 |
| 19 | #N/A | 1911.7 | 2598.0 | 3296.0 | 4151.7 | 4880.7 | 5901.3 | 6304.4 | 7150.6 | 8091.7 | 8964.8 | 9909.5 | 10450.6 | 11452.8 | 12200.7 | 12931.8 |
| 20 | #N/A | 4006.3 | 5673.7 | 7117.5 | 8781.7 | 9939.3 | 12146.8 | 13136.7 | 14539.6 | 16785.1 | #mem | #mem | #mem | #mem | #mem | #N/A |
Delphi is limited to allocating $7FFFFFFF bytes when using GetMem or SetLength.
(GetMem and SetLength are defined as taking a 32-bit integer, even in 64-bit applications)
This means that N=20,r=16 requires 128*16*2^20 = 0x80000000 bytes of memory.
This exceeds the amount you can ask for in an 32-bit Integer.
In practice, your limit in a 32-bit process will be lower, given the 2GB limit of virtual address space,
and that there are other things already in your address space (e.g. your application, dlls).
References
==============
The scrypt Password-Based Key Derivation Function
http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-02
Java implementation of scrypt
https://github.com/wg/scrypt
Scrypt For Node/IO
https://github.com/barrysteyn/node-scrypt
*)
{$IFDEF CONDITIONALEXPRESSIONS}
{$IF CompilerVersion >= 15} //15 = Delphi 7
{$DEFINE COMPILER_7_UP}
{$IFEND}
{$IF CompilerVersion = 15} //15 = Delphi 7
{$DEFINE COMPILER_7}
{$DEFINE COMPILER_7_DOWN}
{$IFEND}
{$ELSE}
{$IFDEF VER130} //Delphi 5
{$DEFINE COMPILER_7_DOWN}
{$DEFINE COMPILER_5_DOWN}
{$DEFINE COMPILER_5}
{$DEFINE MSWINDOWS} //Delphi 5 didn't define MSWINDOWS back then. And there was no other platform
{$ENDIF}
{$ENDIF}
interface
uses
SysUtils
{$IFDEF COMPILER_7_UP}, Types{$ENDIF};
{$IFNDEF UNICODE}
type
UnicodeString = WideString;
{$ENDIF}
{$IFDEF COMPILER_7} //Delphi 7
type
TBytes = Types.TByteDynArray; //TByteDynArray wasn't added until around Delphi 7. Sometime later it moved to SysUtils.
{$ENDIF}
{$IFDEF COMPILER_5} //Delphi 5
type
TBytes = array of Byte; //for old-fashioned Delphi 5, we have to do it ourselves
IInterface = IUnknown;
TStringDynArray = array of String;
EOSError = EWin32Error;
const
RaiseLastOSError: procedure = SysUtils.RaiseLastWin32Error; //First appeared in Delphi 7
{$ENDIF}
type
//As basic of a Hash interface as you can get
IHashAlgorithm = interface(IInterface)
['{985B0964-C47A-4212-ADAA-C57B26F02CCD}']
function GetBlockSize: Integer;
function GetDigestSize: Integer;
{ Methods }
procedure HashData(const Buffer; BufferLen: Integer);
function Finalize: TBytes;
{ Properties }
property BlockSize: Integer read GetBlockSize;
property DigestSize: Integer read GetDigestSize;
end;
IHmacAlgorithm = interface(IInterface)
['{815787A8-D5E7-41C0-9F23-DF30D1532C49}']
function GetDigestSize: Integer;
function HashData(const Key; KeyLen: Integer; const Data; DataLen: Integer): TBytes;
property DigestSize: Integer read GetDigestSize;
end;
IPBKDF2Algorithm = interface(IInterface)
['{93BB60D0-2C87-46CB-8A2A-A711F0BBEF0D}']
function GetBytes(const Password: UnicodeString; const Salt; const SaltLength: Integer; IterationCount, DesiredBytes: Integer): TBytes;
end;
TScrypt = class(TObject)
protected
procedure BurnBytes(var data: TBytes);
class function StringToUtf8(const Source: UnicodeString): TBytes;
class function Base64Encode(const data: array of Byte): string;
class function Base64Decode(const s: string): TBytes;
class function Tokenize(const s: string; Delimiter: Char): TStringDynArray;
function GenerateSalt: TBytes;
class procedure XorBlockInPlace(var A; const B; Length: Integer);
function PBKDF2(const Password: UnicodeString; const Salt; const SaltLength: Integer; IterationCount, DesiredBytes: Integer): TBytes;
procedure Salsa20InPlace(var Input); //four round version of Salsa20, termed Salsa20/8
function BlockMix(const B: array of Byte): TBytes; //mixes r 128-byte blocks
function ROMix(const B; BlockSize, CostFactor: Cardinal): TBytes;
function GenerateScryptSalt(const Passphrase: UnicodeString; const Salt: array of Byte; const CostFactor, BlockSizeFactor, ParallelizationFactor: Integer): TBytes;
function DeriveBytes(const Passphrase: UnicodeString; const Salt: array of Byte; const CostFactor, BlockSizeFactor, ParallelizationFactor: Integer; DesiredBytes: Integer): TBytes;
procedure GetDefaultParameters(out CostFactor, BlockSizeFactor, ParallelizationFactor: Cardinal);
function TryParseHashString(HashString: string; out CostFactor, BlockSizeFactor, ParallelizationFactor: Cardinal; out Salt: TBytes; out Data: TBytes): Boolean;
function FormatPasswordHash(const costFactor, blockSizeFactor, parallelizationFactor: Integer; const Salt, DerivedBytes: array of Byte): string;
public
constructor Create;
//Get a number of bytes using the default Cost and Parallelization factors
class function GetBytes(const Passphrase: UnicodeString; const Salt: UnicodeString; nDesiredBytes: Integer): TBytes; overload;
//Get a number of bytes, specifying the desired cost and parallelization factor
class function GetBytes(const Passphrase: UnicodeString; const Salt: UnicodeString; CostFactor, BlockSizeFactor, ParallelizationFactor: Cardinal; DesiredBytes: Integer): TBytes; overload;
{
Scrypt is not meant for password storage; it is meant for key generation.
But people can still use it for password hashing.
Unlike Bcrypt, there is no standard representation for passwords hashed with Scrypt.
So we can make one, and provide the function to validate it
}
class function HashPassword(const Passphrase: UnicodeString): string; overload;
class function HashPassword(const Passphrase: UnicodeString; CostFactor, BlockSizeFactor, ParallelizationFactor: Cardinal): string; overload;
class function CheckPassword(const Passphrase: UnicodeString; ExpectedHashString: string; out PasswordRehashNeeded: Boolean): Boolean;
{
Let people have access to our hash functions. They've been tested and verified, and they work well.
Besides, we have HMAC and PBKDF2. That's gotta be useful for someone.
}
class function CreateObject(ObjectName: string): IInterface;
end;
EScryptException = class(Exception);
implementation
{$IFDEF UnitTests}
{$DEFINE ScryptUnitTests}
{$ENDIF}
{$IFDEF NoScryptUnitTests}
{$UNDEF ScryptUnitTests}
{$ENDIF}
uses
{$IFDEF ScryptUnitTests}ScryptTests,{$ENDIF}
{$IFDEF MSWINDOWS}Windows, ComObj, ActiveX,{$ENDIF}
Math;
{$IFDEF COMPILER_7_DOWN}
function MAKELANGID(p, s: WORD): WORD;
begin
Result := WORD(s shl 10) or p;
end;
function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean; overload;
begin
Result := C in CharSet;
end;
type
UInt64 = Int64;
PUInt64 = ^UInt64;
{$ENDIF}
const
SCRYPT_HASH_LEN = 64; //This can be user defined - but this is the reference size
//The normal Base64 alphabet
Base64EncodeTable: array[0..63] of Char =
{ 0:} 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+
{26:} 'abcdefghijklmnopqrstuvwxyz'+
{52:} '0123456789+/';
Base64DecodeTable: array[#0..#127] of Integer = (
{ 0:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ________________
{ 16:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ________________
{ 32:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // _______________/
{ 48:} 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 0123456789______
{ 64:} -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // _ABCDEFGHIJKLMNO
{ 80:} 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, // PQRSTUVWXYZ_____
{ 96:} -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // _abcdefghijklmno
{113:} 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1); // pqrstuvwxyz_____
//Unix password file use non-standard base64 alphabet
BsdBase64EncodeTable: array[0..63] of Char =
{ 0:} './'+
{ 2:} 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+
{28:} 'abcdefghijklmnopqrstuvwxyz'+
{54:} '0123456789';
BsdBase64DecodeTable: array[#0..#127] of Integer = (
{ 0:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ________________
{ 16:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // ________________
{ 32:} -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, // ______________./
{ 48:} 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, // 0123456789______
{ 64:} -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, // _ABCDEFGHIJKLMNO
{ 80:} 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, // PQRSTUVWXYZ_____
{ 96:} -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, // _abcdefghijklmno
{113:} 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1); // pqrstuvwxyz_____
type
PLongWordArray = ^TLongWordArray_Unsafe;
TLongWordArray_Unsafe = array[0..79] of LongWord; //SHA uses an array of 80 elements
const
//Cryptography Service Provider (CSP) items
CALG_SHA1 = $00008004;
CALG_SHA_256 = $0000800c;
type
//Cryptography Next Generation (Cng) items
BCRYPT_HANDLE = THandle;
BCRYPT_ALG_HANDLE = THandle;
BCRYPT_KEY_HANDLE = THandle;
BCRYPT_HASH_HANDLE = THandle;
NTSTATUS = Cardinal;
const
// Microsoft built-in providers. (OpenAlgorithmProvider.pszImplementation)
MS_PRIMITIVE_PROVIDER: UnicodeString = 'Microsoft Primitive Provider';
MS_PLATFORM_CRYPTO_PROVIDER: UnicodeString = 'Microsoft Platform Crypto Provider'; //i.e. TPM
// OpenAlgorithmProvider.AlgorithmID
BCRYPT_SHA256_ALGORITHM = 'SHA256';
// OpenAlgorithmProvider.dwFlags
BCRYPT_ALG_HANDLE_HMAC_FLAG = $00000008;
// BCryptGetProperty property name
BCRYPT_OBJECT_LENGTH: UnicodeString = 'ObjectLength';
var
_BCryptInitialized: Boolean = False;
_BCryptAvailable: Boolean = False;
_BCryptOpenAlgorithmProvider: function(out hAlgorithm: BCRYPT_ALG_HANDLE; pszAlgId, pszImplementation: PWideChar; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptCloseAlgorithmProvider: function(hAlgorithm: BCRYPT_ALG_HANDLE; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptGetProperty: function(hObject: BCRYPT_HANDLE; pszProperty: PWideChar; {out}pbOutput: Pointer; cbOutput: Cardinal; out cbResult: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptCreateHash: function(hAlgorithm: BCRYPT_ALG_HANDLE; out hHash: BCRYPT_HASH_HANDLE; pbHashObject: Pointer; cbHashObject: Cardinal; pbSecret: Pointer; cbSecret: Cardinal; dwFlags: DWORD): NTSTATUS; stdcall;
_BCryptHashData: function(hHash: BCRYPT_HASH_HANDLE; pbInput: Pointer; cbInput: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptFinishHash: function(hHash: BCRYPT_HASH_HANDLE; pbOutput: Pointer; cbOutput: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptDestroyHash: function(hHash: BCRYPT_HASH_HANDLE): NTSTATUS; stdcall;
_BCryptGenRandom: function({In_opt}hAlgorithm: BCRYPT_ALG_HANDLE; {Inout}pbBuffer: Pointer; cbBuffer: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall;
_BCryptDeriveKeyPBKDF2: function(hPrf: BCRYPT_ALG_HANDLE; pbPassword: Pointer; cbPassword: Cardinal; pbSalt: Pointer; cbSalt: Cardinal; cIterations: UInt64; pbDerivedKey: Pointer; cbDerivedKey: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall;
function FormatNTStatusMessage(const NTStatusMessage: NTSTATUS): string;
var
Buffer: PChar;
Len: Integer;
Hand: HMODULE;
begin
{
KB259693: How to translate NTSTATUS error codes to message strings
Obtain the formatted message for the given Win32 ErrorCode
Let the OS initialize the Buffer variable. Need to LocalFree it afterward.
}
Hand := SafeLoadLibrary('ntdll.dll');
Len := FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER or
FORMAT_MESSAGE_FROM_SYSTEM or
// FORMAT_MESSAGE_IGNORE_INSERTS or
// FORMAT_MESSAGE_ARGUMENT_ARRAY or
FORMAT_MESSAGE_FROM_HMODULE,
Pointer(Hand),
NTStatusMessage, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
@Buffer, 0, nil);
try
//Remove the undesired line breaks and '.' char
while (Len > 0) and (CharInSet(Buffer[Len - 1], [#0..#32, '.'])) do Dec(Len);
//Convert to Delphi string
SetString(Result, Buffer, Len);
finally
//Free the OS allocated memory block
LocalFree(HLOCAL(Buffer));
end;
FreeLibrary(Hand);
end;
procedure NTStatusCheck(Status: NTSTATUS);
const
SNTError = 'NT Error 0x%.8x: %s';
begin
if (Status and $80000000) = 0 then //00: success, 01:information, 10: warning, 11: error
Exit;
raise EOleSysError.CreateFmt(SNTError, [
HResultFromNT(Status),
FormatNTStatusMessage(Status)
]);
end;
function RRot32(const X: LongWord; const c: Byte): LongWord; //inline;
begin
//Any use of assembly is dwarfed by the fact that ASM functions cannot be inlined
//Which forces a function call. Which drops us from 82MB/s -> 50 MB/s
Result := (X shr c) or (X shl (32-c));
end;
function LRot32(X: LongWord; c: Byte): LongWord; //inline;
{IFDEF PUREPASCAL}
begin
Result := (X shl c) or (X shr (32-c));
{ELSE !PUREPASCAL}
(* {$IFDEF CPUX86}
asm
MOV cl, c;
ROL eax, cl;
{$ENDIF CPUX86}
{$IFDEF CPUX64}
//http://blogs.msdn.com/b/oldnewthing/archive/2004/01/14/58579.aspx
//In x64 calling convention the first four parameters are passed in rcx, rdx, r8, r9
//Return value is in RAX
asm
MOV eax, ecx; //store result in eax
MOV cl, c; //rol left only supports from rolling from cl
ROL eax, cl;
{$ENDIF}
*)
{ENDIF !PUREPASCAL}
end;
function ByteSwap(const X: Cardinal): Cardinal; //inline;
begin
{
Reverses the byte order of a 32-bit register.
}
Result :=
( X shr 24) or
((X shr 8) and $00FF00) or
((X shl 8) and $FF0000) or
( X shl 24);
end;
procedure RaiseOSError(ErrorCode: DWORD; Msg: string);
var
ex: EOSError;
begin
ex := EOSError.Create(Msg);
ex.ErrorCode := error;
raise Ex;
end;
type
HCRYPTPROV = THandle;
HCRYPTHASH = THandle;
HCRYPTKEY = THandle;
ALG_ID = LongWord; //unsigned int
{ SHA1 implemented in PurePascal}
type
TSHA1 = class(TInterfacedObject, IHashAlgorithm)
private
FInitialized: Boolean;
FHashLength: TULargeInteger; //Number of bits put into the hash
FHashBuffer: array[0..63] of Byte; //one step before W0..W15
FHashBufferIndex: Integer; //Current position in HashBuffer
FABCDEBuffer: array[0..4] of LongWord; //working hash buffer is 160 bits (20 bytes)
procedure Compress;
procedure UpdateLen(NumBytes: LongWord);
procedure Burn;
protected
procedure HashCore(const Data; DataLen: Integer);
function HashFinal: TBytes;
function GetBlockSize: Integer;
function GetDigestSize: Integer;
procedure Initialize;
public
constructor Create;
procedure HashData(const Buffer; BufferLen: Integer);
function Finalize: TBytes;
procedure SelfTest;
end;
{
SHA-1 implemented by Microsoft Crypto Service Provider (CSP)
}
TCspHash = class(TInterfacedObject, IHashAlgorithm)
private
FProvider: HCRYPTPROV;
FAlgorithmID: Cardinal; //CALG_SHA1, CALG_SHA256
FBlockSize: Integer; //CSP doesn't provide a way to get the block size of a hash
FHash: HCRYPTHASH;
protected
function GetBlockSize: Integer; //SHA-1 compresses in blocks of 64 bytes
function GetDigestSize: Integer; //SHA-1 digest is 20 bytes (160 bits)
procedure Initialize;
procedure Burn;
procedure HashCore(const Data; DataLen: Integer);
function HashFinal: TBytes;
public
constructor Create(AlgorithmID: Cardinal; BlockSize: Integer);
destructor Destroy; override;
procedure HashData(const Buffer; BufferLen: Integer);
function Finalize: TBytes;
end;
{
Hash algorithms provided by the Microsoft Cryptography Next Generation (Cng) Provider
}
TCngHash = class(TInterfacedObject, IHashAlgorithm, IHmacAlgorithm)
private
FHmacMode: Boolean;
FAlgorithm: BCRYPT_ALG_HANDLE;
FAlgorithmBlockSize: Integer;
FAlgorithmDigestSize: Integer;
FHashObjectBuffer: TBytes;
FHash: BCRYPT_HASH_HANDLE;
class function GetBcryptAlgorithmBlockSize(Algorithm: BCRYPT_ALG_HANDLE): Integer;
class function GetBcryptAlgorithmDigestSize(Algorithm: BCRYPT_ALG_HANDLE): Integer;
protected
procedure RequireBCrypt;
function GetBlockSize: Integer; //e.g. SHA-1 compresses in blocks of 64 bytes
function GetDigestSize: Integer; //e.g. SHA-1 digest is 20 bytes (160 bits)
class function InitializeBCrypt: Boolean;
procedure Initialize;
procedure Burn;
procedure HashCore(Hash: BCRYPT_HASH_HANDLE; const Data; DataLen: Integer);
function HashFinal(Hash: BCRYPT_HASH_HANDLE): TBytes;
public
constructor Create(const AlgorithmID: UnicodeString; const Provider: PWideChar; HmacMode: Boolean);
destructor Destroy; override;
class function IsAvailable: Boolean;
{ IHashAlgorithm }
procedure HashData(const Buffer; BufferLen: Integer); overload;
function Finalize: TBytes;
{ IHmacAlgoritm }
function HashData(const Key; KeyLen: Integer; const Data; DataLen: Integer): TBytes; overload;
end;
{
SHA256 implemented in Pascal
}
type
TSHA256 = class(TInterfacedObject, IHashAlgorithm)
private
FInitialized: Boolean;
FHashLength: TULargeInteger; //Number of bits put into the hash
FHashBuffer: array[0..63] of Byte; //one step before W0..W15
FHashBufferIndex: Integer; //Current position in HashBuffer
FCurrentHash: array[0..7] of LongWord;
procedure Compress;
procedure UpdateLen(NumBytes: LongWord);
procedure Burn;
protected
function GetBlockSize: Integer;
function GetDigestSize: Integer;
procedure HashCore(const Data; DataLen: Integer);
function HashFinal: TBytes;
procedure Initialize;
public
constructor Create;
procedure HashData(const Buffer; BufferLen: Integer);
function Finalize: TBytes;
end;
{
SHA-256 implemented by Microsoft Crypto Service Provider (CSP)
}
THmac = class(TInterfacedObject, IHmacAlgorithm)
private
FHash: IHashAlgorithm;
protected
function GetDigestSize: Integer;
public
constructor Create(Hash: IHashAlgorithm);
function HashData(const Key; KeyLen: Integer; const Data; DataLen: Integer): TBytes;
end;
TRfc2898DeriveBytes = class(TInterfacedObject, IPBKDF2Algorithm)
private
FHMAC: IHmacAlgorithm;
public
constructor Create(HMAC: IHmacAlgorithm);
function GetBytes(const Password: UnicodeString; const Salt; const SaltLength: Integer; IterationCount, DesiredBytes: Integer): TBytes;
end;
TBCryptDeriveKeyPBKDF2 = class(TInterfacedObject, IPBKDF2Algorithm)
private
FAlgorithm: BCRYPT_ALG_HANDLE;
public
constructor Create(const AlgorithmID: UnicodeString; const Provider: PWideChar);
function GetBytes(const Password: UnicodeString; const Salt; const SaltLength: Integer; IterationCount, DesiredBytes: Integer): TBytes;
end;
{ TScrypt }
class function TScrypt.GetBytes(const Passphrase, Salt: UnicodeString; nDesiredBytes: Integer): TBytes;
var
scrypt: TScrypt;
saltUtf8: TBytes;
costFactor, blockSizeFactor, parallelizationFactor: Cardinal;
begin
saltUtf8 := TScrypt.StringToUtf8(Salt);
scrypt := TScrypt.Create;
try
scrypt.GetDefaultParameters(costFactor, blockSizeFactor, parallelizationFactor);
Result := scrypt.DeriveBytes(Passphrase, saltUtf8, costFactor, blockSizeFactor, parallelizationFactor, nDesiredBytes);
finally
scrypt.Free;
end;
end;
procedure TScrypt.GetDefaultParameters(out CostFactor, BlockSizeFactor, ParallelizationFactor: Cardinal);
const
N_interactive = 14; //14 ==> 2^14 = 16,384
// N_sensitive = 20; //20 ==> 2^20 = 1,048,576
r = 8;
p = 1;
var
t1, t2, freq: Int64;
duration: Real;
testCostFactor: Cardinal;
begin
{
The time to run a full scrypt is linear in memory used; although CPU is slightly faster with doubled r over doubled N.
Canonical scrypt runs a benchmark with N=14, r=1 (i.e. 128*1*2^14 = 128*1*16384 = 2MB)
We'll do a 2MB benchmark, but using r=8, N=11 (i.e. 128*8*2^11 = 128*8* 2048 = 2MB)
The target for a normal user is 250-500 ms
}
CostFactor := 14; //i.e. 2^14 = 16,384 iterations
BlockSizefactor := 8; //will operate on 128*8 = 1,024 byte blocks, and randomly access 128*8*2^14 = 16 MB of memory during the calculation
ParallelizationFactor := 1;
//Benchmark the current computer, and see if it could be faster than 250ms to compute a hash
testCostFactor := 11;
QueryPerformanceCounter(t1);
TScrypt.HashPassword('Benchmark', testCostFactor, 8, 1);
QueryPerformanceCounter(t2);
if not QueryPerformanceFrequency({var}freq) then Exit;
duration := (t2-t1)/freq*1000;
//Each single increase in CostFactor will double the execution time.
//We don't want the execution time to exceed 500ms
while (duration < 250) do
begin
duration := duration*2;
testCostFactor := testCostFactor+1;
end;
//And we certainly won't go any lower than the default 14,8,1 (anyone remember 8,N,1 anymore?)
if testCostFactor > CostFactor then
begin
OutputDebugString(PChar(Format('Increasing scrypt cost factor from default %d up to %d', [CostFactor, testCostFactor])));
CostFactor := testCostFactor;
end;
end;
class function TScrypt.Base64Decode(const s: string): TBytes;
function Char64(character: Char): Integer;
begin
if (Ord(character) > Length(Base64DecodeTable)) then
begin
Result := -1;
Exit;
end;
Result := Base64DecodeTable[character];
end;
procedure Append(value: Byte);
var
i: Integer;
begin
i := Length(Result);
SetLength(Result, i+1);
Result[i] := value;
end;
var
i: Integer;
len: Integer;
c1, c2, c3, c4: Integer;
begin
SetLength(Result, 0);
len := Length(s);
i := 1;
while i <= len do
begin
// We'll need to have at least 2 character to form one byte.
// Anything less is invalid
if (i+1) > len then
raise EScryptException.Create('Invalid base64 hash string');
c1 := Char64(s[i ]);
c2 := Char64(s[i+1]);
c3 := Char64(s[i+2]);
c4 := Char64(s[i+3]);
Inc(i, 4);
if (c1 = -1) or (c2 = -1) then
raise EScryptException.Create('Invalid base64 hash string');
//Now we have at least one byte in c1|c2
// c1 = ..111111
// c2 = ..112222
Append( ((c1 and $3f) shl 2) or (c2 shr 4) );
if (c3 = -1) then
Exit;
//Now we have the next byte in c2|c3
// c2 = ..112222
// c3 = ..222233
Append( ((c2 and $0f) shl 4) or (c3 shr 2) );
//If there's a 4th caracter, then we can use c3|c4 to form the third byte
if (c4 = -1) then
Exit;
//Now we have the next byte in c3|c4
// c3 = ..222233
// c4 = ..333333
Append( ((c3 and $03) shl 6) or c4 );
end;
end;
class function TScrypt.Base64Encode(const data: array of Byte): string;
const
b64: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function EncodePacket(b1, b2, b3: Byte; Len: Integer): string;
begin
{
11111111 22222222 33333333
\____/\_____/\_____/\____/
| | | |
c1 c2 c3 c4
}
Result := '====';
Result[1] := Base64EncodeTable[b1 shr 2];
Result[2] := Base64EncodeTable[((b1 and $03) shl 4) or (b2 shr 4)];
if Len < 2 then Exit;
Result[3] := Base64EncodeTable[((b2 and $0f) shl 2) or (b3 shr 6)];
if Len < 3 then Exit;
Result[4] := Base64EncodeTable[b3 and $3f];
end;
var
i: Integer;
len: Integer;
b1, b2: Integer;
begin
Result := '';
len := Length(data);
if len = 0 then
Exit;
//encode whole 3-byte chunks TV4S 6ytw fsfv kgY8 jIuc Drjc 8deX 1s.
i := Low(data);
while len >= 3 do
begin
Result := Result+EncodePacket(data[i], data[i+1], data[i+2], 3);
Inc(i, 3);
Dec(len, 3);
end;
if len = 0 then
Exit;
//encode partial final chunk
Assert(len < 3);
if len >= 1 then
b1 := data[i]
else
b1 := 0;
if len >= 2 then
b2 := data[i+1]
else
b2 := 0;
Result := Result+EncodePacket(b1, b2, 0, len);
end;
function TScrypt.BlockMix(const B: array of Byte): TBytes;
var
r: Integer;
X: array[0..15] of LongWord;
i: Integer;
Y: TBytes;
ne, no: Integer; //index even, index odd
begin
{
Mix r 128-byte blocks (which is equivalent of saying 2r 64-byte blocks)
}
//Make sure we actually have an even multiple of 128 bytes
if Length(B) mod 128 <> 0 then
raise EScryptException.Create('');
r := Length(B) div 128;
SetLength(Y, 128*r);
//X <- B[2*r-1]
//Copy last 64-byte block into X.
Move(B[64*(2*r-1)], X[0], 64);
for i := 0 to 2*r-1 do
begin
//T = X xor B[i]
TScrypt.XorBlockInPlace(X[0], B[64*i], 64);
//X = Salsa (T)
Self.Salsa20InPlace(X[0]);
//Y[i] = X
Move(X[0], Y[64*i], 64);
end;
{
Result = Y[0],Y[2],Y[4], ..., Y[2*r-2], Y[1],Y[3],Y[5], ..., Y[2*r-1]
Result[ 0] := Y[ 0];
Result[ 1] := Y[ 2];
Result[ 2] := Y[ 4];
Result[ 3] := Y[ 6];
Result[ 4] := Y[ 8];
Result[ 5] := Y[10];
Result[ 6] := Y[ 1];
Result[ 7] := Y[ 3];
Result[ 8] := Y[ 5];
Result[ 9] := Y[ 7];
Result[10] := Y[ 9];
Result[11] := Y[11];
Result[ 0] := Y[ 0];
Result[ 6] := Y[ 1];
Result[ 1] := Y[ 2];
Result[ 7] := Y[ 3];
Result[ 2] := Y[ 4];
Result[ 8] := Y[ 5];
Result[ 3] := Y[ 6];
Result[ 9] := Y[ 7];
Result[ 4] := Y[ 8];
Result[10] := Y[ 9];
Result[ 5] := Y[10];
Result[11] := Y[11];
}
SetLength(Result, Length(B));
i := 0;
ne := 0;
no := r;
while (i <= 2*r-1) do
begin
Move(Y[64*(i )], Result[64*ne], 64);
Move(Y[64*(i+1)], Result[64*no], 64);
Inc(ne, 1);
Inc(no, 1);
Inc(i, 2);
end;
end;
procedure TScrypt.BurnBytes(var data: TBytes);
begin
if Length(data) <= 0 then
Exit;
FillChar(data[Low(data)], Length(data), 0);
SetLength(data, 0);
end;
class function TScrypt.CheckPassword(const Passphrase: UnicodeString; ExpectedHashString: string; out PasswordRehashNeeded: Boolean): Boolean;
var
scrypt: TScrypt;
costFactor, blockSizeFactor, parallelizationFactor: Cardinal;
salt, expected, actual: TBytes;
t1, t2, freq: Int64;
duration: Real;
const
SCouldNotParsePassword = 'Could not parse expected password hash';
begin
{
Validate the supplied password against the saved hash.
Returns
True: If the password is valid
False: If the password is invalid
PasswordRehashNeeded
Contains true if the user's password should be re-hashed and the new hash stored in the database.
The typical reason for rehashing is that the hash took less than the minimum 250ms to compute. The target is 250-500ms.
Another reason would be if the scrypt version has been updated, and the stored hash needs to be updated to the new
version.
Contains false if the password does not need to be rehashed.
}
Result := False;
PasswordRehashNeeded := False;
scrypt := TScrypt.Create;
try
if not scrypt.TryParseHashString(ExpectedHashString, {out}costFactor, blockSizeFactor, parallelizationFactor, salt, expected) then
raise EScryptException.Create(SCouldNotParsePassword);
try
QueryPerformanceCounter(t1);
actual := scrypt.DeriveBytes(Passphrase, salt, costFactor, blockSizeFactor, ParallelizationFactor, Length(expected));
QueryPerformanceCounter(t2);
if Length(actual) <> Length(expected) then
Exit;
Result := CompareMem(@expected[0], @actual[0], Length(expected));
if Result then
begin
//Only advertise a rehash being needed if they got the correct password.
//Don't want someone blindly re-hashing with a bad password because they forgot to check the result,
//or because they decided to handle "PasswordRehashNeeded" first.
if QueryPerformanceFrequency(freq) then