-
Notifications
You must be signed in to change notification settings - Fork 65
/
DECHashAuthentication.pas
1655 lines (1505 loc) · 58.2 KB
/
DECHashAuthentication.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
{*****************************************************************************
The DEC team (see file NOTICE.txt) licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. A copy of this licence is found in the root directory
of this project in the file LICENCE.txt or alternatively at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*****************************************************************************}
/// <summary>
/// Unit containing all the KDF, MGF, HMAC and PBKDF2 algorithms
/// </summary>
unit DECHashAuthentication;
interface
uses
{$IFDEF FPC}
SysUtils, Classes,
{$ELSE}
System.SysUtils, System.Classes, Generics.Collections,
{$ENDIF}
DECBaseClass, DECHashBase, DECHashInterface, DECTypes , DECFormatBase;
{$INCLUDE DECOptions.inc}
type
/// <summary>
/// Type of the KDF variant
/// </summary>
TKDFType = (ktKDF1, ktKDF2, ktKDF3);
/// <summary>
/// Meta class for the class containing the password hash specific properties
/// </summary>
TDECPasswordHashClass = class of TDECPasswordHash;
/// <summary>
/// Class containing all the KDF, MGF, HMAC and PBKDF2 algorithms
/// </summary>
TDECHashAuthentication = class(TDECHash)
strict private
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// IEEE P1363 Working Group, ISO 18033-2:2004
/// This is either KDF1 or KDF2 depending on KDFType
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="DataSize">
/// Size in bytes of the source data passed.
/// </param>
/// <param name="Seed">
/// Start value for pseudo random number generator
/// </param>
/// <param name="SeedSize">
/// Size of the seed in byte.
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <param name="KDFType">
/// Type of the algorithm: 1 = KDF1, 2 = KDF2 and 3 = KDF 3
/// </param>
/// <returns>
/// Returns the new derrived key.
/// </returns>
class function KDFInternal(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer;
KDFType: TKDFType): TBytes; inline;
public
/// <summary>
/// Detects whether the given hash class is one particularily suited
/// for storing hashes of passwords
/// </summary>
/// <returns>
/// true if it's a hash class specifically designed to store password
/// hashes, false for ordinary hash algorithms.
/// </returns>
class function IsPasswordHash: Boolean; override;
// mask generation
/// <summary>
/// Mask generation: generates an output based on the data given which is
/// similar to a hash function but in contrast does not have a fixed output
/// length. Use of a MGF is desirable in cases where a fixed-size hash
/// would be inadequate. Examples include generating padding, producing
/// one time pads or keystreams in symmetric key encryption, and yielding
/// outputs for pseudorandom number generators.
/// Indexed Mask generation function, IEEE P1363 working group
/// equal to KDF1 except without seed. RFC 2437 PKCS #1
/// </summary>
/// <param name="Data">
/// Data from which to generate a mask from
/// </param>
/// <param name="DataSize">
/// Size of the input data in bytes
/// </param>
/// <param name="MaskSize">
/// Size of the returned mask in bytes
/// </param>
/// <returns>
/// Mask such that one cannot determine the data which had been given to
/// generate this mask from.
/// </returns>
class function MGF1(const Data; DataSize, MaskSize: Integer): TBytes; overload;
/// <summary>
/// Mask generation: generates an output based on the data given which is
/// similar to a hash function but incontrast does not have a fixed output
/// length. Use of a MGF is desirable in cases where a fixed-size hash
/// would be inadequate. Examples include generating padding, producing
/// one time pads or keystreams in symmetric key encryption, and yielding
/// outputs for pseudorandom number generators
/// </summary>
/// <param name="Data">
/// Data from which to generate a mask from
/// </param>
/// <param name="MaskSize">
/// Size of the returned mask in bytes
/// </param>
/// <returns>
/// Mask such that one cannot determine the data which had been given to
/// generate this mask from.
/// </returns>
class function MGF1(const Data: TBytes; MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// IEEE P1363 Working Group, ISO 18033-2:2004
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="DataSize">
/// Size in bytes of the source data passed.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="SeedSize">
/// Size of the seed/salt in byte.
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
/// <remarks>
/// In earlier versions there was an optional format parameter. This has
/// been removed as this is a base class. The method might not have
/// returned a result with the MaskSize specified, as the formatting might
/// have had to alter this. This would have been illogical.
/// </remarks>
class function KDF1(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// IEEE P1363 Working Group, ISO 18033-2:2004
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
class function KDF1(const Data, Seed: TBytes;
MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// IEEE P1363 Working Group, ISO 18033-2:2004
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="DataSize">
/// Size in bytes of the source data passed.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="SeedSize">
/// Size of the seed/salt in byte.
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
/// <remarks>
/// In earlier versions there was an optional format parameter. This has
/// been removed as this is a base class. The method might not have
/// returned a result with the MaskSize specified, as the formatting might
/// have had to alter this. This would have been illogical.
/// </remarks>
class function KDF2(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// IEEE P1363 Working Group, ISO 18033-2:2004
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="Seed">
/// Start value for pseudo random number generator
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
class function KDF2(const Data, Seed: TBytes;
MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="DataSize">
/// Size in bytes of the source data passed.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="SeedSize">
/// Size of the seed/salt in byte.
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
/// <remarks>
/// In earlier versions there was an optional format parameter. This has
/// been removed as this is a base class. The method might not have
/// returned a result with the MaskSize specified, as the formatting might
/// have had to alter this. This would have been illogical.
/// </remarks>
class function KDF3(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
class function KDF3(const Data, Seed: TBytes;
MaskSize: Integer): TBytes; overload;
// DEC's own KDF + MGF
/// <summary>
/// Key deviation algorithm to derrive keys from other keys. The alrorithm
/// implemented by this method does not follow any official standard.
/// </summary>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="DataSize">
/// Size in bytes of the source data passed.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="SeedSize">
/// Size of the seed/salt in byte.
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <param name="Index">
/// Optional parameter: can be used to specify a different default value
/// for the index variable used in the algorithm.
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
class function KDFx(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer;
Index: UInt32 = 1): TBytes; overload;
/// <summary>
/// Key deviation algorithm to derrive keys from other keys.
/// </summary>
/// <remarks>
/// This variant of the algorithm does not follow an official standard.
/// It has been created by the original author of DEC.
/// </remarks>
/// <param name="Data">
/// Source data from which the new key shall be derrived.
/// </param>
/// <param name="Seed">
/// Salt value
/// </param>
/// <param name="MaskSize">
/// Size of the generated output in byte
/// </param>
/// <param name="Index">
/// Optional parameter: can be used to specify a different default value
/// for the index variable used in the algorithm.
/// </param>
/// <returns>
/// Returns the new derrived key with the length specified in MaskSize.
/// </returns>
class function KDFx(const Data, Seed: TBytes; MaskSize: Integer;
Index: UInt32 = 1): TBytes; overload;
/// <summary>
/// Mask generation: generates an output based on the data given which is
/// similar to a hash function but incontrast does not have a fixed output
/// length. Use of a MGF is desirable in cases where a fixed-size hash
/// would be inadequate. Examples include generating padding, producing
/// one time pads or keystreams in symmetric key encryption, and yielding
/// outputs for pseudorandom number generators.
/// </summary>
/// <remarks>
/// This variant of the algorithm does not follow an official standard.
/// It has been created by the original author of DEC.
/// </remarks>
/// <param name="Data">
/// Data from which to generate a mask from
/// </param>
/// <param name="DataSize">
/// Size of the passed data in bytes
/// </param>
/// <param name="MaskSize">
/// Size of the returned mask in bytes
/// </param>
/// <param name="Index">
/// Looks like this is a salt applied to each byte of output data?
{ TODO : Clarify this parameter }
/// </param>
/// <returns>
/// Mask such that one cannot determine the data which had been given to
/// generate this mask from.
/// </returns>
class function MGFx(const Data; DataSize, MaskSize: Integer;
Index: UInt32 = 1): TBytes; overload;
/// <summary>
/// Mask generation: generates an output based on the data given which is
/// similar to a hash function but incontrast does not have a fixed output
/// length. Use of a MGF is desirable in cases where a fixed-size hash
/// would be inadequate. Examples include generating padding, producing
/// one time pads or keystreams in symmetric key encryption, and yielding
/// outputs for pseudorandom number generators.
/// </summary>
/// <remarks>
/// This variant of the algorithm does not follow an official standard.
/// It has been created by the original author of DEC.
/// </remarks>
/// <param name="Data">
/// Data from which to generate a mask from
/// </param>
/// <param name="MaskSize">
/// Size of the returned mask in bytes
/// </param>
/// <param name="Index">
/// Looks like this is a salt applied to each byte of output data?
{ TODO : Clarify this parameter }
/// </param>
/// <returns>
/// Mask such that one cannot determine the data which had been given to
/// generate this mask from.
/// </returns>
class function MGFx(const Data: TBytes; MaskSize: Integer;
Index: UInt32 = 1): TBytes; overload;
/// <summary>
/// HMAC according to rfc2202: hash message authentication code allow to
/// verify both the data integrity and the authenticity of a message.
/// </summary>
/// <param name="Key">
/// This is the secret key which shall not be transmitted over the line.
/// The sender uses this key to create the resulting HMAC, transmits the
/// text and the HMAC over the line and the receiver recalculates the HMAC
/// based on his copy of the secret key. If his calculated HMAC equals the
/// transfered HMAC value the message has not been tampered.
/// </param>
/// <param name="Text">
/// Text over which to calculate the HMAC
/// </param>
/// <returns>
/// Calculated HMAC
/// </returns>
class function HMAC(const Key, Text: TBytes): TBytes; overload;
/// <summary>
/// HMAC according to rfc2202: hash message authentication code allow to
/// verify both the data integrity and the authenticity of a message.
/// </summary>
/// <param name="Key">
/// This is the secret key which shall not be transmitted over the line.
/// The sender uses this key to create the resulting HMAC, transmits the
/// text and the HMAC over the line and the receiver recalculates the HMAC
/// based on his copy of the secret key. If his calculated HMAC equals the
/// transfered HMAC value the message has not been tampered.
/// </param>
/// <param name="Text">
/// Text over which to calculate the HMAC
/// </param>
/// <returns>
/// Calculated HMAC
/// </returns>
class function HMAC(const Key, Text: RawByteString): TBytes; overload;
/// <summary>
/// Password based key deviation function 2
/// RFC 2898, PKCS #5.
/// This can be used to create a login sheme by storing the output,
/// number of iterations and the salt. When the user enters a password
/// this calculation is done using the same parameters as stored for his
/// user account and comparing the output.
/// </summary>
/// <param name="Password">
/// Password to create the deviation from
/// </param>
/// <param name="Salt">
/// Salt used to modify the password
/// </param>
/// <param name="Iterations">
/// Number of iterations to perform
/// </param>
/// <param name="KeyLength">
/// Length of the resulting key in byte
/// </param>
/// <returns>
/// The calculated PBKDF2 value
/// </returns>
class function PBKDF2(const Password, Salt: TBytes; Iterations: Integer;
KeyLength: Integer): TBytes; overload;
/// <summary>
/// Password based key deviation function 2
/// RFC 2898, PKCS #5.
/// This can be used to create a login sheme by storing the output,
/// number of iterations and the salt. When the user enters a password
/// this calculation is done using the same parameters as stored for his
/// user account and comparing the output.
/// </summary>
/// <param name="Password">
/// Password to create the deviation from
/// </param>
/// <param name="Salt">
/// Salt used to modify the password
/// </param>
/// <param name="Iterations">
/// Number of iterations to perform
/// </param>
/// <param name="KeyLength">
/// Length of the resulting key in byte
/// </param>
/// <returns>
/// The calculated PBKDF2 value
/// </returns>
class function PBKDF2(const Password, Salt: RawByteString;
Iterations: Integer;
KeyLength: Integer): TBytes; overload;
end;
/// <summary>
/// Adds methods which shall not be found in the specialized password hash
/// classes. Mainly the CalcStreamXXX and CalcFileXXX ones. They shall not
/// be contained there as those password hashes usually restrict the maximum
/// length of the data which can be hashed.
/// </summary>
TDECHashExtended = class(TDECHashAuthentication, IDECHashExtended)
/// <summary>
/// Calculates the hash value over a given stream of bytes
/// </summary>
/// <param name="Stream">
/// Memory or file stream over which the hash value shall be calculated.
/// The stream must be assigned. The hash value will always be calculated
/// from the current position of the stream.
/// </param>
/// <param name="Size">
/// Number of bytes within the stream over which to calculate the hash value
/// </param>
/// <param name="HashResult">
/// In this byte array the calculated hash value will be returned
/// </param>
/// <param name="OnProgress">
/// Optional callback routine. It can be used to display the progress of
/// the operation.
/// </param>
procedure CalcStream(const Stream: TStream; Size: Int64; var HashResult: TBytes;
const OnProgress:TDECProgressEvent = nil); overload;
/// <summary>
/// Calculates the hash value over a givens stream of bytes
/// </summary>
/// <param name="Stream">
/// Memory or file stream over which the hash value shall be calculated.
/// The stream must be assigned. The hash value will always be calculated
/// from the current position of the stream.
/// </param>
/// <param name="Size">
/// Number of bytes within the stream over which to calculate the hash value
/// </param>
/// <param name="Format">
/// Optional formatting class. The formatting of that will be applied to
/// the returned hash value.
/// </param>
/// <param name="OnProgress">
/// Optional callback routine. It can be used to display the progress of
/// the operation.
/// </param>
/// <returns>
/// Hash value over the bytes in the stream, formatted with the formatting
/// passed as format parameter, if used.
/// </returns>
function CalcStream(const Stream: TStream; Size: Int64; Format: TDECFormatClass = nil;
const OnProgress:TDECProgressEvent = nil): RawByteString; overload;
/// <summary>
/// Calculates the hash value over a given stream of bytes. The calculated
/// hash value can be retrieved with one of the DigestAsXXX methods.
/// </summary>
/// <param name="Stream">
/// Memory or file stream over which the hash value shall be calculated.
/// The stream must be assigned. The hash value will always be calculated
/// from the current position of the stream.
/// </param>
/// <param name="Size">
/// Number of bytes within the stream over which to calculate the hash value
/// </param>
/// <param name="OnProgress">
/// Optional callback routine. It can be used to display the progress of
/// the operation.
/// </param>
/// <param name="DoFinalize">
/// Optinal parameter: if true this call is the last one and the
/// finalization of the hash calculation, including calling done, will be
/// carried out in this method call as well.
/// </param>
/// <remarks>
/// Before calling this method for the first time after creation of the
/// hash instance or after calling Done Init needs to be called.
/// After calling this method Done needs to be called and in case of
/// algorithms (like SHA3) with a message size in bits and not whole bytes
/// the contents of the last byte needs to be assigned to PaddingByte before
/// calling Done!
/// </remarks>
procedure CalcStream(const Stream: TStream; Size: Int64;
const OnProgress:TDECProgressEvent = nil;
DoFinalize: Boolean = false); overload;
/// <summary>
/// Calculates the hash value over the contents of a given file
/// </summary>
/// <param name="FileName">
/// Path and name of the file to be processed
/// </param>
/// <param name="HashResult">
/// Here the resulting hash value is being returned as byte array
/// </param>
/// <param name="OnProgress">
/// Optional callback. If being used the hash calculation will call it from
/// time to time to return the current progress of the operation
/// </param>
procedure CalcFile(const FileName: string; var HashResult: TBytes;
const OnProgress:TDECProgressEvent = nil); overload;
/// <summary>
/// Calculates the hash value over the contents of a given file
/// </summary>
/// <param name="FileName">
/// Path and name of the file to be processed
/// </param>
/// <param name="Format">
/// Optional parameter: Formatting class. If being used the formatting is
/// being applied to the returned string with the calculated hash value
/// </param>
/// <param name="OnProgress">
/// Optional callback. If being used the hash calculation will call it from
/// time to time to return the current progress of the operation
/// </param>
/// <returns>
/// Calculated hash value as RawByteString.
/// </returns>
/// <remarks>
/// We recommend to use a formatting which results in 7 bit ASCII chars
/// being returned, otherwise the conversion into the RawByteString might
/// result in strange characters in the returned result.
/// </remarks>
function CalcFile(const FileName: string; Format: TDECFormatClass = nil;
const OnProgress:TDECProgressEvent = nil): RawByteString; overload;
end;
/// <summary>
/// All hash classes with hash algorithms specially developed for password
/// hashing should inherit from this class in order to be able to distinguish
/// those from normal hash algorithms not really meant to be used for password
/// hashing.
/// </summary>
TDECPasswordHash = class(TDECHashAuthentication, IDECHashPassword)
strict private
/// <summary>
/// Sets the salt value given. Throws an EDECHashException if a salt is
/// passed which is longer than MaxSaltLength.
/// </summary>
/// <exception cref="EDECHashException">
/// Exception raised if length of <c>Value</c> is not in the range of
/// <c>MinSaltLength</c> and <c>MaxSaltLength</c>
/// </exception>
procedure SetSalt(const Value: TBytes);
/// <summary>
/// Returns the defined salt value
/// </summary>
function GetSalt: TBytes;
strict protected
/// <summary>
/// Most, if not all password hashing algorithms (like bcrypt) have a salt
/// parameter to modify the entered password value.
/// </summary>
FSalt : TBytes;
/// <summary>
/// Overwrite the salt value
/// </summary>
procedure DoDone; override;
{$Region CryptFormatHandling}
/// <summary>
/// Returns the ID code for Crypt/BSD like storing of passwords. The ID
/// has to start with the $ at the beginning and does not contain a
/// trailing $.
/// </summary>
/// <returns>
/// If the algorithm on which this is being used is a Crypt/BSD compatible
/// password hash algorithm the ID is returned otherwise an empty string.
/// </returns>
class function GetCryptID:string; virtual;
/// <summary>
/// Returns the parameters required for the crypt-like password storing
/// in that format.
/// </summary>
/// <param name="Params">
/// Algorithm specific parameters used for initialization. For details see
/// documentation of the concrete implementation in the algorithm.
/// </param>
/// <param name="Format">
/// Format class for formatting the output
/// </param>
/// <returns>
/// Returns an empty string if the the algorithm on which this is being
/// used is not a Crypt/BSD compatible password hash algorithm
/// </returns>
function GetCryptParams(const Params : string;
Format : TDECFormatClass):string; virtual;
/// <summary>
/// Returns the salt required for the crypt-like password storing
/// in that format.
/// </summary>
/// <param name="Salt">
/// The raw salt value
/// </param>
/// <param name="Format">
/// Format class for formatting the output
/// </param>
function GetCryptSalt(const Salt : TBytes;
Format : TDECFormatClass):string; virtual;
/// <summary>
/// Returns the hash required for the crypt-like password storing
/// in that format. If a salt etc. is needed that needs to be scepcified
/// before calling this method.
/// </summary>
/// <param name="Password">
/// Password entered which shall be hashed.
/// </param>
/// <param name="Params">
/// Algorithm specific parameters used for initialization. For details see
/// documentation of the concrete implementation in the algorithm.
/// </param>
/// <param name="Salt">
/// Salt value used by the password hash calculation. Depending on the
/// value of SaltIsRaw, the salt needs to specified in raw encoding or
/// in the encoding used in the Crypt/BSD password storage string.
/// </param>
/// <param name="Salt">
/// Salt value used by the password hash calculation in binary raw format,
/// means not Radix64 encoded or so.
/// </param>
/// <param name="Format">
/// Format class for formatting the output
/// </param>
/// <returns>
/// Returns an empty string if the the algorithm on which this is being
/// used is not a Crypt/BSD compatible password hash algorithm.
/// </returns>
function GetCryptHash(Password : TBytes;
const Params : string;
const Salt : TBytes;
Format : TDECFormatClass):string; virtual;
{$EndRegion}
public
/// <summary>
/// Returns the maximum length of a salt value given for the algorithm
/// in byte
/// </summary>
function MaxSaltLength:UInt8; virtual; abstract;
/// <summary>
/// Returns the minimum length of a salt value given for the algorithm
/// in byte
/// </summary>
function MinSaltLength:UInt8; virtual; abstract;
/// <summary>
/// Returns the maximum length of a user supplied password given for the
/// algorithm in byte
/// </summary>
class function MaxPasswordLength:UInt8; virtual; abstract;
{$Region CryptBSDFormatHandlingPublic}
/// <summary>
/// Tries to find a class type by its Crypt identification
/// (e.g. 2a is Bcrypt).
/// </summary>
/// <param name="Identity">
/// Identity to look for, with or without the starting $ delimiter sign.
/// </param>
/// <returns>
/// Returns the class type of the class with the specified identity value
/// or throws an EDECClassNotRegisteredException exception if no class
/// with the given Crypt identity has been found
/// </returns>
/// <exception cref="EDECClassNotRegisteredException">
/// Exception raised if the class specified by <c>Identity</c> is not found
/// </exception>
class function ClassByCryptIdentity(Identity: string): TDECPasswordHashClass;
/// <summary>
/// Calculates a passwort hash for the given password and returns it in
/// a BSDCrypt compatible format. This method only works for those hash
/// algorithms implementing the necessary GetBSDCryptID method.
/// </summary>
/// <param name="Password">
/// Entered password for which to calculate the hash. The caller is
/// responsible to ensure the maximum password length is adhered to.
/// Any exceptions raised due to too long passwords are not caught here!
/// </param>
/// <param name="Params">
/// Algorithm specific parameters used for initialization. For details see
/// documentation of the concrete implementation in the algorithm.
/// </param>
/// <param name="Salt">
/// Salt value used by the password hash calculation. Depending on the
/// value of SaltIsRaw, the salt needs to specified in raw encoding or
/// in the encoding used in the Crypt/BSD password storage string.
/// </param>
/// <param name="SaltIsRaw">
/// If true the passed salt value is a raw value. If false it is encoded
/// like in the Crypt/BSD password storage string.
/// </param>
/// <param name="Format">
/// Formatting class used to format the calculated password. Different
/// algorithms in BSDCrypt use different algorithms so one needs to know
/// which one to pass. See description of the hash class used.
/// </param>
/// <returns>
/// Calculated hash value in BSD crypt style format. Returns an empty
/// string if the algorithm is not a Crypt/BSD style password hash algorithm.
/// </returns>
/// <exception cref="EDECHashException">
/// Exception raised if length of <c>Password</c> is higher than
/// <c>MaxPasswordLength</c> or if a salt with a different length than
/// 128 bit has been specified.
/// </exception>
function GetDigestInCryptFormat(const Password : string;
const Params : string;
const Salt : string;
SaltIsRaw : Boolean;
Format : TDECFormatClass):string; overload;
/// <summary>
/// Calculates a passwort hash for the given password and returns it in
/// a BSDCrypt compatible format. This method only works for those hash
/// algorithms implementing the necessary GetBSDCryptID method.
/// </summary>
/// <param name="Password">
/// Entered password for which to calculate the hash. The caller is
/// responsible to ensure the maximum password length is adhered to.
/// Any exceptions raised due to too long passwords are not caught here!
/// </param>
/// <param name="Params">
/// Algorithm specific parameters used for initialization. For details see
/// documentation of the concrete implementation in the algorithm.
/// </param>
/// <param name="Salt">
/// Salt value used by the password hash calculation. Depending on the
/// value of SaltIsRaw, the salt needs to specified in raw encoding or
/// in the encoding used in the Crypt/BSD password storage string.
/// </param>
/// <param name="SaltIsRaw">
/// If true the passed salt value is a raw value. If false it is encoded
/// like in the Crypt/BSD password storage string.
/// </param>
/// <param name="Format">
/// Formatting class used to format the calculated password. Different
/// algorithms in BSDCrypt use different algorithms so one needs to know
/// which one to pass. See description of the hash class used.
/// </param>
/// <returns>
/// Calculated hash value in BSD crypt style format. Returns an empty
/// string if the algorithm is not a Crypt/BSD style password hash algorithm.
/// </returns>
/// <exception cref="EDECHashException">
/// Exception raised if length of <c>Password</c> is higher than
/// <c>MaxPasswordLength</c> or if a salt with a different length than
/// 128 bit has been specified.
/// </exception>
function GetDigestInCryptFormat(Password : TBytes;
const Params : string;
const Salt : string;
SaltIsRaw : Boolean;
Format : TDECFormatClass):string; overload; virtual;
/// <summary>
/// Checks whether a given password is the correct one for a password
/// storage "record"/entry in Crypt/BSD format.
/// </summary>
/// <param name="Password">
/// Password to check for validity
/// </param>
/// <param name="CryptData">
/// The data needed to "compare" the password against in Crypt/BSD like
/// format: $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
/// The exact format depends on the algorithm used.
/// </param>
/// <param name="Format">
/// Must be the right type for the Crypt/BSD encoding used by the
/// algorithm used. This was implemented this way to avoid making the
/// DECHashAuthentication unit dependant on the DECFormat unit not needed
/// otherwise.
/// </param>
/// <returns>
/// True if the password given is correct.
/// </returns>
function IsValidPassword(const Password : string;
const CryptData : string;
Format : TDECFormatClass): Boolean; overload;
/// <summary>
/// Checks whether a given password is the correct one for a password
/// storage "record"/entry in Crypt/BSD format.
/// </summary>
/// <param name="Password">
/// Password to check for validity
/// </param>
/// <param name="CryptData">
/// The data needed to "compare" the password against in Crypt/BSD like
/// format: $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
/// The exact format depends on the algorithm used.
/// </param>
/// <param name="Format">
/// Must be the right type for the Crypt/BSD encoding used by the
/// algorithm used. This was implemented this way to avoid making the
/// DECHashAuthentication unit dependant on the DECFormat unit not needed
/// otherwise.
/// </param>
/// <returns>
/// True if the password given is correct.
/// </returns>
function IsValidPassword(Password : TBytes;
const CryptData : string;
Format : TDECFormatClass): Boolean; overload; virtual;
{$EndRegion}
/// <summary>
/// Defines the salt value used. Throws an EDECHashException if a salt is
/// passed which is longer than MaxSaltLength. The salt has to be passed
/// in binary form. Any Base64 encoded salt needs to be decoded before
/// passing.
/// </summary>
/// <exception cref="EDECHashException">
/// Exception raised if the length of the value assigned is not in the
/// range of <c>MinSaltLength</c> and <c>MaxSaltLength</c>
/// </exception>
property Salt: TBytes
read GetSalt
write SetSalt;
end;
{$IF CompilerVersion < 28.0}
/// <summary>
/// Class helper for implementing array concatenation which is not available
/// in Delphi XE6 or lower.
/// </summary>
/// <remarks>
/// Shall be removed as soon as the minimum supported version is XE7 or higher.
/// </remarks>
TArrHelper = class
class procedure AppendArrays<T>(var A: TArray<T>; const B: TArray<T>);
end;
{$IFEND}
/// <summary>
/// Meta class for the class containing the authentication methods
/// </summary>
TDECHashAuthenticationClass = class of TDECHashAuthentication;
/// <summary>
/// Meta class for the class containing the additional calculation methods
/// </summary>
TDECHashExtendedClass = class of TDECHashExtended;
implementation
uses
DECUtil;
resourcestring
/// <summary>
/// Exception message when specifying a salt value longer than allowed
/// </summary>
sSaltValueTooLong = 'Maximum allowed salt length (%0:d byte) exceeded';
/// <summary>
/// Exception message when specifying a salt value shorter than allowed
/// </summary>
sSaltValueTooShort = 'Minumum allowed salt length (%0:d byte) exceeded';
/// <summary>
/// No class for the given crypt ID has been registered, so that ID is
/// not supported.
/// </summary>
sCryptIDNotRegistered = 'No class for crypt ID %s registered';
class function TDECHashAuthentication.IsPasswordHash: Boolean;
begin
Result := self.InheritsFrom(TDECPasswordHash);
end;
class function TDECHashAuthentication.KDFInternal(const Data; DataSize: Integer; const Seed;
SeedSize, MaskSize: Integer; KDFType: TKDFType): TBytes;
var
I, n,
Rounds, DigestBytes : Integer;
Dest : PByteArray;
Count : UInt32;
HashInstance : TDECHashAuthentication;
begin
SetLength(Result, 0);
DigestBytes := DigestSize;
Assert(MaskSize >= 0);
Assert(DataSize >= 0);
Assert(SeedSize >= 0);
Assert(DigestBytes >= 0);
HashInstance := TDECHashAuthenticationClass(self).Create;
try
Rounds := (MaskSize + DigestBytes - 1) div DigestBytes;
SetLength(Result, Rounds * DigestBytes);
Dest := @Result[0];
if (KDFType = ktKDF2) then
n := 1
else
n := 0;
for I := 0 to Rounds-1 do
begin
Count := SwapUInt32(n);
HashInstance.Init;
if (KDFType = ktKDF3) then
begin
HashInstance.Calc(Count, SizeOf(Count));
HashInstance.Calc(Data, DataSize);
end
else