-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMD6.pas
More file actions
4793 lines (4113 loc) · 169 KB
/
MD6.pas
File metadata and controls
4793 lines (4113 loc) · 169 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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
MD6 calculation
Provides classes and functions for calculation of MD6 hash. All hash widths
that are a multiple of 8 are supported (meaning only whole bytes, arbitrary
bitstreams are not supported). Also, all mandatory and optional hash inputs
can be varied (key, mode control, number of rounds).
Provided implementation (class TMD6Hash and its descendants) allows not
only standard single-thread processing, but as the MD6 can be heavily
parallelized, multi-thread processing mode was also implemented.
WARNING - multi-thread in here means that the internal workings of the
calculations are done in multiple execution paths, it does
NOT mean that the TMD6Hash class is multi-thread capable (ie.
calling its methods from multiple threads)!
NOTE - although the MT processing was tested, I cannot guarantee it is
bug-free and fully correct. Also, performance gain and scaling is
uncertain, as I could not test the code on anything better than
an ancient dual-core CPU (manufactured around year 2006).
Linux build was tested only in virtual machine, so performance and
stability there is also unknown.
Version 2.0.1 (2025-04-09)
Last change 2025-04-12
©2022-2025 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.MD6
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
AuxMath - github.com/TheLazyTomcat/Lib.AuxMath
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
BitOps - github.com/TheLazyTomcat/Lib.BitOps
HashBase - github.com/TheLazyTomcat/Lib.HashBase
InterlockedOps - github.com/TheLazyTomcat/Lib.InterlockedOps
* SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library SimpleCPUID is required only when compiling for x86 architecture (ie.
32bit) and PurePascal symbol is not defined.
Library SimpleCPUID might also be required as an indirect dependency.
Indirect dependencies:
AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit MD6;
{
MD6_PurePascal
If you want to compile this unit without ASM, don't want to or cannot define
PurePascal for the entire project and at the same time you don't want to or
cannot make changes to this unit, define this symbol for the entire project
and only this unit will be compiled in PurePascal mode.
}
{$IFDEF MD6_PurePascal}
{$DEFINE PurePascal}
{$ENDIF}
//------------------------------------------------------------------------------
{$IF Defined(CPUX86_64) or Defined(CPUX64)}
{$DEFINE x64}
{$ELSEIF Defined(CPU386)}
{$DEFINE x86}
{$ELSE}
{$DEFINE PurePascal}
{$IFEND}
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$ELSEIF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH DuplicateLocals+}
{$MODESWITCH ClassicProcVars+}
{$IFNDEF PurePascal}
{$ASMMODE Intel}
{$ENDIF}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
//------------------------------------------------------------------------------
// do not touch following
{$IF not Defined(PurePascal) and Defined(x86)}
{$DEFINE VectorCompression}
{$ELSE}
{$UNDEF VectorCompression}
{$IFEND}
interface
uses
SysUtils, Classes, Contnrs,
AuxTypes, AuxClasses, HashBase;
{===============================================================================
Library-specific exceptions
===============================================================================}
type
EMD6Exception = class(EHASHException);
EMD6InvalidValue = class(EMD6Exception);
EMD6InvalidState = class(EMD6Exception);
EMD6SizeMismatch = class(EMD6Exception);
EMD6IncompatibleClass = class(EMD6Exception);
EMD6OperationNotAllowed = class(EMD6Exception);
EMD6ProcessingError = class(EMD6Exception);
EMD6SemaphoreError = class(EMD6Exception);
{===============================================================================
Common types and constants
===============================================================================}
{
Bytes in all MD6 hashes are always ordered from the most significant byte to
the least significant byte (big endian).
MD6 does not differ in little and big endian form, as it is not a single
quantity, therefore methods like MD6ToLE or MD6ToBE do nothing and are
present only for the sake of completeness.
}
type
TMD6 = packed array of UInt8;
TMD6_224 = packed array[0..27] of UInt8; PMD6_224 = ^TMD6_224;
TMD6_256 = packed array[0..31] of UInt8; PMD6_256 = ^TMD6_256;
TMD6_384 = packed array[0..47] of UInt8; PMD6_384 = ^TMD6_384;
TMD6_512 = packed array[0..63] of UInt8; PMD6_512 = ^TMD6_512;
TMD6Key = packed array of UInt8;
//------------------------------------------------------------------------------
const
ZeroMD6_224: TMD6_224 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
ZeroMD6_256: TMD6_256 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
ZeroMD6_384: TMD6_384 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
ZeroMD6_512: TMD6_512 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
DefaultMD6Bits = 512;
{===============================================================================
--------------------------------------------------------------------------------
TMD6Hash
--------------------------------------------------------------------------------
===============================================================================}
type
// see description of OnThreadStart[*] properties of TMD6Hash class
TMD6ThreadFunction = procedure(Param: Pointer);
TMD6ThreadStartCallback = procedure(Sender: TObject; ThreadFunction: TMD6ThreadFunction; Param: Pointer);
TMD6ThreadStartEvent = procedure(Sender: TObject; ThreadFunction: TMD6ThreadFunction; Param: Pointer) of object;
{===============================================================================
TMD6Hash - class declaration
===============================================================================}
type
TMD6Hash = class(TBlockHash)
protected
fMD6: TMD6;
// md6 parameters (inputs)
fHashBits: Integer;
fKey: TMD6Key;
fRounds: Integer;
fModeControl: Integer;
// processing settings
fMaxThreads: Integer;
fParallelSizeLimit: TMemSize;
// processing variables
fProcessor: TObject;
fProcessing: Boolean;
fWorkerThreads: TObjectList;
// events
fOnThreadStartCallback: TMD6ThreadStartCallback;
fOnThreadStartEvent: TMD6ThreadStartEvent;
// getters setters
Function GetMD6: TMD6; virtual;
procedure SetMD6(Value: TMD6); virtual; // not used as a setter in any property, called only directly
procedure SetHashBits(Value: Integer); virtual;
Function GetKey: TMD6Key; virtual;
procedure SetKey(Value: TMD6Key); virtual;
procedure SetRounds(Value: Integer); virtual;
procedure SetModeControl(Value: Integer); virtual;
procedure SetMaxThreads(Value: Integer); virtual;
// block hash processing
procedure ProcessBlock(const Block); override;
procedure ProcessFirst(const Block); override;
procedure ProcessLast; override;
// multi-thread processing
procedure ThreadStartHandler(Sender: TObject); virtual;
procedure WaitAndFreeThreads; virtual;
procedure ParallelProcessing(Address: Pointer; Size: TMemSize); virtual;
Function ParallelProgressHandler(Progress: Double): Boolean; virtual;
// init/final
procedure Initialize; override;
procedure Finalize; override;
public
{
ProcessorCount
Returns number of processors available in the system. It can be used to
properly set MaxThreads property when configuring multi-thread processing.
}
class Function ProcessorCount: Integer; virtual;
class Function MD6ToLE(MD6: TMD6): TMD6; virtual;
class Function MD6ToBE(MD6: TMD6): TMD6; virtual;
class Function MD6FromLE(MD6: TMD6): TMD6; virtual;
class Function MD6FromBE(MD6: TMD6): TMD6; virtual;
Function HashSize: TMemSize; reintroduce;
class Function HashName: String; override;
class Function HashEndianness: THashEndianness; override;
class Function HashFinalization: Boolean; override;
{
CreateAndInitFrom
WARNING - first overload (accepting THashBase parameter) will fail,
raising an exception, if the source object is currently
processing in multi-thread or parallel mode.
}
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TMD6); overload; virtual;
procedure Init; override;
procedure Final; override;
procedure HashBuffer(const Buffer; Size: TMemSize); override;
procedure HashStream(Stream: TStream; Count: Int64 = -1); override;
Function Compare(Hash: THashBase): Integer; override;
Function AsString: String; override;
procedure FromString(const Str: String); override;
procedure FromStringDef(const Str: String; const Default: TMD6); reintroduce; overload; virtual;
procedure SaveToStream(Stream: TStream; Endianness: THashEndianness = heDefault); override;
procedure LoadFromStream(Stream: TStream; Endianness: THashEndianness = heDefault); override;
{
SetupHashBits
Sets HashBits to a passed value, zeroes and, if needed, resizes property
MD6 and also changes property Rounds to a default value calculated using
the following formula:
If Length(Key) > 0 then
Rounds := Max(80,40 + (HashBits / 4))
else
Rounds := 40 + (HashBits / 4)
}
procedure SetupHashBits(HashBits: Integer); virtual;
{
SetupKey
Sets key to a selected value and changes property Rounds accordingly - see
description of method SetupHashBits for details.
If Key is shorter than 64 bytes, then it is back-padded with zero bytes.
If it is longer, then it is truncated and only first 64 bytes are used.
String key is converted to UTF8-encoded string and this new string is then
used "as is" (ie. as an array of bytes) for the actual key.
}
procedure SetupKey(const Key; Size: TMemSize); overload; virtual;
procedure SetupKey(const Key: array of Byte); overload; virtual;
procedure SetupKey(const Key: String); overload; virtual;
{
BreakProcessing
See class THashBase in library HashBase for explanation of this method.
It is overriden here to allow for termination of worker threads in multi-
thread or parallel processing.
}
Function BreakProcessing: Boolean; override;
property MD6: TMD6 read GetMD6;
{
HashBits
Length (size) of the resulting hash in bits. Only whole bytes - arbitrary
bit lengths are not supported.
Can be in range from 8 up to and including 512 (default is 512). Setting
invalid or unsupported value will raise an exception.
Assigning value to HashBits also clears (sets to all-zero) and resizes the
MD6 property (always, not only when the value is changed) - no other input
is changed (see method SetupHashBits).
}
property HashBits: Integer read fHashBits write SetHashBits;
{
Key
Key used in hashing (integral part of MD6 specification) as an byte array.
Allowed lengths are from 0 to 64 bytes. If you use longer key, then an
exception is raised. Default value is an empty key (zero length, nil array).
NOTE - when setting the key using this property, then no other MD6 input
parameter is changed (see method SetupKey for more information).
}
property Key: TMD6Key read GetKey write SetKey;
{
Rounds
Number of computing rounds performed on each processed block - internal
thing, see MD6 specification for details. More rounds, more security,
less paranoia :D.
Can be any positive number, but avoid setting it to a very large value
(eg. for default 512bit hash, it is 168). Using negative value will raise
an exception. Default value depends on other parameters (hash bits and
key), but at the object creation it is set to 168.
}
property Rounds: Integer read fRounds write SetRounds;
{
ModeControl
This number controls how the hashing mechanism operates internally,
therefore its value should not be important for the user (but changing it
still changes the resulting hash). You should be only aware that it affects
memory consumptions (bigger value means more memory is needed) and
parallelization potential (again bigger means higher potential). So if you
want, for example, to limit memory use, set it to a low value.
Accepted range is from 0 to 64, default value is 64. Note that values from
27 and up are all computationally equivalent (mathematical thing - see MD6
specification for explanation).
Mode control of zero completely rules out use of multi-thread or parallel
processing.
}
property ModeControl: Integer read fModeControl write SetModeControl;
{
MaxThreads
This number determines whether processing should be run synchronously in
the context of calling thread (ie. single-thread processing), or using
multiple execution paths (multi-thread or parallel processing - and yes,
these are distinct modes, see further down).
It can be set to any number above zero (default value is 1, meaning single
thread processing). Using value of zero or lower raises an exception.
NOTE - this number is capped at 1024. Assigning higher number will not
raise an exception, but the value will be silently lowered to the
limit.
WARNING - it is not recommended to use value higher than is number of
processors available in the system (see method ProcessorCount).
Also, very high number may lead to an excessive memory use.
Value of one (1) forces the execution to run in a sigle thread (the calling
thread), value above one enables multi-thread or parallel execution and
also sets limit on how many working threads can be spawned (use method
ProcessorCount to get how many threads can run truly concurently).
But note that it only enables multi-thread or parallel processing, not
forces it. Whether it will be used depends also on mode control (must be
above zero) and in case of parallel processing also on data size (see
property ParallelSizeLimit for details on size limit).
Multi-thread processing mode works the same as single-thread processing,
ie. it runs under the standard init-update-final interface. Meaning no
matter how you hash the data (uncluding macro functions), it can be used
if enabled (including on zero-size data).
Parallel processing mode is different - it can only be run on data that are
in its entirety present in memory (so buffers, strings, streams descending
from TCustomMemoryStream), therefore it is approached only from selected
macro functions and run directly, without using standard i-u-f interface.
NOTE - nature of parallel processing means the progress reporting might
not work entirely as expected (it will be reported not based on
amount of already processed data, but in specific time intervals).
}
property MaxThreads: Integer read fMaxThreads write SetMaxThreads;
{
ParallelSizeLimit
Minimum size (in bytes) of a memory buffer that can be processed using
parallel mode if that is enabled (by setting property MaxThreads to value
above 1 and ModeControl above 0).
If parallel processing is enabled, but the buffer is smaller than this
limit, then it will be done using standard multi-thread processing instead
of fully parallel one.
Any value is allowed (setting it to zero effectively disables this limit),
default is 4MiB (4194304 bytes).
}
property ParallelSizeLimit: TMemSize read fParallelSizeLimit write fParallelSizeLimit;
{
OnThreadStart[*]
This event or callback (note event is called first, and if it IS assigned
then callback is NOT called) is called when the hashing is running in
multiple threads (multi-thread or parallel processing) and a new worker
thread needs to be spawned.
These are here to give user control over spawning and lifetime of worker
(background) threads (eg. using effective thread pooling when performing
many hashings in a row).
Handler of this event will receive two arguments (well, three when counting
Sender) - ThreadFunction and Param. You must, before the handler returns,
pass both these arguments to a thread of your choice, This thread must then
immediately execute ThreadFunction while passing given Param to it.
While ThreadFunction is executing, do NOT pause or kill the thread - that
would create number of errors and deadlocks. Manipulating thread priority
or affinity is allowed - it should not affect the processing apart from
possible performance effects.
When the function ends (returns), you can do whatever you want with the
thread within which it was executing (destroy it, pool it for further
use, stare at it, ...), it will not be referenced or used by internal
workings of this library in any capacity.
How many times and when these events are called can be completely arbitrary,
do not assume any such quantity!
NOTE - the handlers are called in the context of thread that is managing
the current instance (ie. thread that is calling method Update).
If neither of these events is assigned, then worker thread is spawned using
internal means and its lifetime is also managed internally - this is ok for
sporadic hashing, but if many hashes are calculated in rapid succession,
then performance might suffer as each hash will spawn and then destroy its
own set of worker threads.
}
property OnThreadStartCallback: TMD6ThreadStartCallback read fOnThreadStartCallback write fOnThreadStartCallback;
property OnThreadStartEvent: TMD6ThreadStartEvent read fOnThreadStartEvent write fOnThreadStartEvent;
property OnThreadStart: TMD6ThreadStartEvent read fOnThreadStartEvent write fOnThreadStartEvent;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMD6DefHash
--------------------------------------------------------------------------------
===============================================================================}
{
This is a common ancestor for classes that provide predefined MD6 variants -
that is variants with invariant hash length and other inputs set strictly to
their default values.
}
{===============================================================================
TMD6DefHash - class declaration
===============================================================================}
type
TMD6DefHash = class(TMD6Hash)
protected
procedure SetMD6(Value: TMD6); override;
procedure SetHashBits(Value: Integer); override;
procedure SetKey(Value: TMD6Key); override;
procedure SetRounds(Value: Integer); override;
procedure SetModeControl(Value: Integer); override;
public
procedure SetupHashBits(HashBits: Integer); override;
// it is enough to override the first overload of SetupKey as it is called by all others
procedure SetupKey(const Key; Size: TMemSize); overload; override;
// the input parameters are made read-only (only default values will be used)
property HashBits: Integer read fHashBits;
property Key: TMD6Key read GetKey;
property Rounds: Integer read fRounds;
property ModeControl: Integer read fModeControl;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMD6_224Hash
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMD6_224Hash - class declaration
===============================================================================}
type
TMD6_224Hash = class(TMD6DefHash)
protected
Function GetMD6_224: TMD6_224; virtual;
procedure Initialize; override;
public
class Function MD6_224ToLE(MD6: TMD6_224): TMD6_224; virtual;
class Function MD6_224ToBE(MD6: TMD6_224): TMD6_224; virtual;
class Function MD6_224FromLE(MD6: TMD6_224): TMD6_224; virtual;
class Function MD6_224FromBE(MD6: TMD6_224): TMD6_224; virtual;
class Function HashName: String; override;
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TMD6); overload; override;
constructor CreateAndInitFrom(Hash: TMD6_224); overload; virtual;
procedure FromStringDef(const Str: String; const Default: TMD6_224); overload; virtual;
property MD6_224: TMD6_224 read GetMD6_224;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMD6_256Hash
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMD6_256Hash - class declaration
===============================================================================}
type
TMD6_256Hash = class(TMD6DefHash)
protected
Function GetMD6_256: TMD6_256; virtual;
procedure Initialize; override;
public
class Function MD6_256ToLE(MD6: TMD6_256): TMD6_256; virtual;
class Function MD6_256ToBE(MD6: TMD6_256): TMD6_256; virtual;
class Function MD6_256FromLE(MD6: TMD6_256): TMD6_256; virtual;
class Function MD6_256FromBE(MD6: TMD6_256): TMD6_256; virtual;
class Function HashName: String; override;
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TMD6); overload; override;
constructor CreateAndInitFrom(Hash: TMD6_256); overload; virtual;
procedure FromStringDef(const Str: String; const Default: TMD6_256); overload; virtual;
property MD6_256: TMD6_256 read GetMD6_256;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMD6_384Hash
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMD6_384Hash - class declaration
===============================================================================}
type
TMD6_384Hash = class(TMD6DefHash)
protected
Function GetMD6_384: TMD6_384; virtual;
procedure Initialize; override;
public
class Function MD6_384ToLE(MD6: TMD6_384): TMD6_384; virtual;
class Function MD6_384ToBE(MD6: TMD6_384): TMD6_384; virtual;
class Function MD6_384FromLE(MD6: TMD6_384): TMD6_384; virtual;
class Function MD6_384FromBE(MD6: TMD6_384): TMD6_384; virtual;
class Function HashName: String; override;
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TMD6); overload; override;
constructor CreateAndInitFrom(Hash: TMD6_384); overload; virtual;
procedure FromStringDef(const Str: String; const Default: TMD6_384); overload; virtual;
property MD6_384: TMD6_384 read GetMD6_384;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMD6_512Hash
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMD6_512Hash - class declaration
===============================================================================}
type
TMD6_512Hash = class(TMD6DefHash)
protected
Function GetMD6_512: TMD6_512; virtual;
procedure Initialize; override;
public
class Function MD6_512ToLE(MD6: TMD6_512): TMD6_512; virtual;
class Function MD6_512ToBE(MD6: TMD6_512): TMD6_512; virtual;
class Function MD6_512FromLE(MD6: TMD6_512): TMD6_512; virtual;
class Function MD6_512FromBE(MD6: TMD6_512): TMD6_512; virtual;
class Function HashName: String; override;
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TMD6); overload; override;
constructor CreateAndInitFrom(Hash: TMD6_512); overload; virtual;
procedure FromStringDef(const Str: String; const Default: TMD6_512); overload; virtual;
property MD6_512: TMD6_512 read GetMD6_512;
end;
{===============================================================================
--------------------------------------------------------------------------------
Standalone functions
--------------------------------------------------------------------------------
===============================================================================}
{
Note that there is, for the sake of simplicity, no processing function
implemented for fixed-length hash types (eg. TMD6_224), only for variant-
length type TMD6. If you want to pass a fixed type, or convert variant-length
result to fixed type, use following conversion functions to do so.
}
Function MD6ToMD6_224(Hash: TMD6): TMD6_224;
Function MD6ToMD6_256(Hash: TMD6): TMD6_256;
Function MD6ToMD6_384(Hash: TMD6): TMD6_384;
Function MD6ToMD6_512(Hash: TMD6): TMD6_512;
Function MD6_224ToMD6(Hash: TMD6_224): TMD6;
Function MD6_256ToMD6(Hash: TMD6_256): TMD6;
Function MD6_384ToMD6(Hash: TMD6_384): TMD6;
Function MD6_512ToMD6(Hash: TMD6_512): TMD6;
Function IsCompatibleMD6_224(Hash: TMD6): Boolean;
Function IsCompatibleMD6_256(Hash: TMD6): Boolean;
Function IsCompatibleMD6_384(Hash: TMD6): Boolean;
Function IsCompatibleMD6_512(Hash: TMD6): Boolean;
//------------------------------------------------------------------------------
Function MD6ToStr(MD6: TMD6): String;
Function StrToMD6(Str: String): TMD6;
Function TryStrToMD6(const Str: String; out MD6: TMD6): Boolean;
Function StrToMD6Def(const Str: String; Default: TMD6): TMD6;
Function CompareMD6(A,B: TMD6): Integer;
Function SameMD6(A,B: TMD6): Boolean;
Function BinaryCorrectMD6(Hash: TMD6): TMD6;
//------------------------------------------------------------------------------
type
TMD6Settings = record
HashBits: Integer;
Rounds: Integer;
ModeControl: Integer;
Key: TMD6Key;
end;
const
DefaultMD6Settings: TMD6Settings = (
HashBits: DefaultMD6Bits;
Rounds: 168;
ModeControl: 64;
Key: nil);
// to get default value for any input, use constant DefaultMD6Settings and its fields
Function MD6Settings(HashBits,Rounds,ModeControl: Integer; Key: TMD6Key = nil): TMD6Settings; overload;
Function MD6Settings(HashBits,Rounds,ModeControl: Integer; const Key; KeySize: TMemSize): TMD6Settings; overload;
Function MD6Settings(HashBits,Rounds,ModeControl: Integer; const Key: String): TMD6Settings; overload;
// in all following overloads, Rounds is calculated from HashBits and Key
Function MD6Settings(HashBits,ModeControl: Integer; Key: TMD6Key = nil): TMD6Settings; overload;
Function MD6Settings(HashBits,ModeControl: Integer; const Key; KeySize: TMemSize): TMD6Settings; overload;
Function MD6Settings(HashBits,ModeControl: Integer; const Key: String): TMD6Settings; overload;
Function MD6Settings(HashBits: Integer; Key: TMD6Key = nil): TMD6Settings; overload;
Function MD6Settings(HashBits: Integer; const Key; KeySize: TMemSize): TMD6Settings; overload;
Function MD6Settings(HashBits: Integer; const Key: String): TMD6Settings; overload;
//------------------------------------------------------------------------------
{
For MD6, it is not enough to pass hash from previous step when doing
continuous hashing (BufferMD6 > LastBufferMD6). TDM6State type is introduced
for this purpose.
}
type
TMD6State = type Pointer;
Function InitialMD6(Settings: TMD6Settings): TMD6State; overload;
Function InitialMD6(HashBits: Integer = DefaultMD6Bits): TMD6State; overload;
procedure BufferMD6(State: TMD6State; const Buffer; Size: TMemSize); overload;
Function LastBufferMD6(var State: TMD6State; const Buffer; Size: TMemSize): TMD6;
//------------------------------------------------------------------------------
Function BufferMD6(const Buffer; Size: TMemSize; Settings: TMD6Settings): TMD6; overload;
Function BufferMD6(const Buffer; Size: TMemSize; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
Function AnsiStringMD6(const Str: AnsiString; Settings: TMD6Settings): TMD6; overload;
Function AnsiStringMD6(const Str: AnsiString; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
Function WideStringMD6(const Str: WideString; Settings: TMD6Settings): TMD6; overload;
Function WideStringMD6(const Str: WideString; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
Function StringMD6(const Str: String; Settings: TMD6Settings): TMD6; overload;
Function StringMD6(const Str: String; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
Function StreamMD6(Stream: TStream; Count: Int64; Settings: TMD6Settings): TMD6; overload;
Function StreamMD6(Stream: TStream; Count: Int64 = -1; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
Function FileMD6(const FileName: String; Settings: TMD6Settings): TMD6; overload;
Function FileMD6(const FileName: String; HashBits: Integer = DefaultMD6Bits): TMD6; overload;
//------------------------------------------------------------------------------
type
TMD6Context = type Pointer;
Function MD6_Init(Settings: TMD6Settings): TMD6Context; overload;
Function MD6_Init(HashBits: Integer = DefaultMD6Bits): TMD6Context; overload;
procedure MD6_Update(Context: TMD6Context; const Buffer; Size: TMemSize);
Function MD6_Final(var Context: TMD6Context; const Buffer; Size: TMemSize): TMD6; overload;
Function MD6_Final(var Context: TMD6Context): TMD6; overload;
Function MD6_Hash(const Buffer; Size: TMemSize; HashBits: Integer = DefaultMD6Bits): TMD6;
implementation
uses
{$IFDEF Windows}Windows,{$ELSE}UnixType, BaseUnix,{$ENDIF} SyncObjs,
{$IFDEF VectorCompression}SimpleCPUID,{$ENDIF}AuxMath, StrRect, BitOps,
InterlockedOps;
{$IFNDEF Windows}
{$LINKLIB C}
{$LINKLIB PTHREAD}
{$ENDIF}
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
Imported (external/system) functions
===============================================================================}
{$IFDEF Windows}
procedure GetNativeSystemInfo(lpSystemInfo: PSystemInfo); stdcall; external kernel32;
Function SwitchToThread: BOOL; stdcall; external kernel32;
{$ELSE}
const
_SC_NPROCESSORS_ONLN = 84;
Function sysconf(name: cInt): cLong; cdecl; external;
Function sched_yield: cint; cdecl; external;
Function errno_ptr: pcInt; cdecl; external name '__errno_location';
type
psem_t = ^sem_t;
Function sem_init(sem: psem_t; pshared: cint; value: cunsigned): cint; cdecl; external;
Function sem_destroy(sem: psem_t): cint; cdecl; external;
Function sem_wait(sem: psem_t): cint; cdecl; external;
Function sem_post(sem: psem_t): cint; cdecl; external;
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TMD6ProcessorBase
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMD6ProcessorBase - implementation constants and types
===============================================================================}
const
MD6_BITS_DEFAULT = DefaultMD6Bits{512};
MD6_BITS_MAX = 512;
MD6_BYTES_MAX = MD6_BITS_MAX div 8;
MD6_MODE_DEFAULT = 64;
MD6_KEY_MAXLEN = 8; // words
MD6_KEY_MAXSIZE = 64; // in bytes
MD6_CHUNK_LEN = 16; // words
MD6_CHUNK_SIZE = 128; // bytes (16 words)
MD6_CHUNK_BITS = 1024;
MD6_BLOCK_CHUNKS = 4;
MD6_BLOCK_SIZE = 512; // bytes (64 words)
MD6_BLOCKARRAY_MINLEN = 89; // words
MD6_BLOCKARRAY_IDX_KEY = 15;
MD6_BLOCKARRAY_IDX_U = 23; // position of unique node ID word
MD6_BLOCKARRAY_IDX_V = 24; // position of control word
MD6_BLOCKARRAY_IDX_DATA = 25;
//------------------------------------------------------------------------------
type
TMD6Word = UInt64;
TMD6BlockArray = array of TMD6Word;
TMD6BlockChunks = array[0..Pred(MD6_BLOCK_CHUNKS)] of Pointer;
//------------------------------------------------------------------------------
const
// fractional part of sqrt(6)
MD6_VEC_Q: array[0..14] of TMD6Word = (
TMD6Word($7311c2812425cfa0), TMD6Word($6432286434aac8e7),
TMD6Word($b60450e9ef68b7c1), TMD6Word($e8fb23908d9f06f1),
TMD6Word($dd2e76cba691e5bf), TMD6Word($0cd0d63b2c30bc41),
TMD6Word($1f8ccf6823058f8a), TMD6Word($54e5ed5b88e3775d),
TMD6Word($4ad12aae0a6d6031), TMD6Word($3e7f16bb88222e0d),
TMD6Word($8af8671d3fb50c2c), TMD6Word($995ad1178bd25c31),
TMD6Word($c878c1dd04c4b633), TMD6Word($3b72066c7a1552ac),
TMD6Word($0d6f3522631effcb));
MD6_S_0 = TMD6Word($0123456789abcdef);
MD6_S_MASK = TMD6Word($7311c2812425cfa0);
(*
--------------------------------------------------------------------------------
Following constants are not used anywhere in the code, they are instead
directly expanded into numerals where needed or calculated on-the-fly.
--------------------------------------------------------------------------------
{
Round constants MD6_S can be calculated like this:
MD6_S[0] := MD6_S_0;
For i := 1 to High(MD6_S) do
MD6_S[i] := ROL(MD6_S[i - 1],1) xor (MD6_S[i - 1] and MD6_S_MASK)
}
MD6_S: array[0..167] of TMD6Word = (
TMD6Word($0123456789ABCDEF), TMD6Word($0347CACE1376567E),
TMD6Word($058E571C26C8EADC), TMD6Word($0A1CEC3869911F38),
TMD6Word($16291870F3233150), TMD6Word($3E5330E1C66763A0),
TMD6Word($4EB7614288EB84E0), TMD6Word($DF7F828511F68D60),
TMD6Word($EDEE878B23C997E1), TMD6Word($BADD8D976792A863),
TMD6Word($47AA9BAFEB25D8E7), TMD6Word($CC55B5DEF66E796E),
TMD6Word($D8BAEB3DC8F8BBFD), TMD6Word($E165147A91D1FC5B),
TMD6Word($A3CB28F523A234B7), TMD6Word($6497516B67646DCF),
TMD6Word($A93FE2D7EAEC961E), TMD6Word($736E072EF5FDAA3D),
TMD6Word($95DC0C5DCFDEDE5A), TMD6Word($3AA818BA9BB972B5),
TMD6Word($475031F53753A7CA), TMD6Word($CDB0636B4AA6C814),
TMD6Word($DA7084D795695829), TMD6Word($E6F1892E2EF3F873),
TMD6Word($AFF2925C79C638C7), TMD6Word($7CF5A6B8D388790F),
TMD6Word($89FACFF1A710BB1E), TMD6Word($12E55D626A21FD3D),
TMD6Word($37CBFAC4F462375A), TMD6Word($5C963709CCE469B4),
TMD6Word($E93C6C129DEC9AC8), TMD6Word($B36898253FFDBF11),
TMD6Word($55D1B04B5BDEF123), TMD6Word($FAB2E097B7B92366),
TMD6Word($877501AE4B5345ED), TMD6Word($0DFB03DC96A7CE7B),
TMD6Word($1AE70539296A52D6), TMD6Word($27CF0A7372F4E72C),
TMD6Word($6C9F16E7C5CD0978), TMD6Word($B92F2F4E8F9F1BD0),
TMD6Word($435F5C9D1B3B3C21), TMD6Word($C5AFF9BB36577462),
TMD6Word($CA5E33F748ABACE5), TMD6Word($D6AC656F9176D56B),
TMD6Word($FF588ADE22C96FF7), TMD6Word($8DA1973C6593904F),
TMD6Word($1A42AC78EF26A09F), TMD6Word($2685D8F1FA69C1BE),
TMD6Word($6F0A7162D4F242DC), TMD6Word($BD14A2C5ADC4C738),
TMD6Word($4B39C70A7F8D4951), TMD6Word($D5624C14DB1FDBA2),
TMD6Word($FBC4D829B63A7CE5), TMD6Word($848970524854B56B),
TMD6Word($0913A0A490ADEFF7), TMD6Word($1336C1C9217E104E),
TMD6Word($357D431362D8209C), TMD6Word($5BEBC427E5B041B8),
TMD6Word($E4D6484EEF40C2D0), TMD6Word($A9BCD09DFA814721),
TMD6Word($726961BAD503C963), TMD6Word($96D383F5AE065BE6),
TMD6Word($3FB6856A7808FC6D), TMD6Word($4C7D8AD4D01134FA),
TMD6Word($D8EA9729A0236D54), TMD6Word($E1D5AC52606797A9),
TMD6Word($A2BAD8A4E0EAA8F3), TMD6Word($676571C9E1F5D947),
TMD6Word($ADCBA312E3CE7B8E), TMD6Word($7A96C425E798BC9D),
TMD6Word($873D484AEB31F5BA), TMD6Word($0D6BD095F6422ED5),
TMD6Word($1BD661AAC884532A), TMD6Word($24BC83D5910CE574),
TMD6Word($6969852A221D0FC8), TMD6Word($B3D28A54643F1010),
TMD6Word($54B596A8EC5B2021), TMD6Word($F97AAFD1FCB74062),
TMD6Word($83E5DD22DD4BC0E5), TMD6Word($04CA7A45BE96416B),
TMD6Word($0994B68A5928C3F6), TMD6Word($1239EF94B271444C),
TMD6Word($36621DA944C3CC98), TMD6Word($5EC43BD38D8655B0),
TMD6Word($EF8875261F08EEC0), TMD6Word($BC10AA4C3A111301),
TMD6Word($4831D69854232503), TMD6Word($D0726FB0AC674F06),
TMD6Word($F0F49DE17CEBD10D), TMD6Word($91F9BB43DDF6631B),
TMD6Word($32E2F486BFC88537), TMD6Word($57C5298D5B918F4E),
TMD6Word($FC8B539BB722919C), TMD6Word($8917E5B64A65A2B9),
TMD6Word($133E0BEC94EEC7D3), TMD6Word($356C15592DF94826),
TMD6Word($5BD82AB37FD3D86C), TMD6Word($E4A057E7DBA678F8),
TMD6Word($A940ED4EB768B951), TMD6Word($73811A9D4AF1FBA3),
TMD6Word($940337BB95C23CE6), TMD6Word($38076DF62F84756D),
TMD6Word($400F9B6C7B0CAFFA), TMD6Word($C01EB4D8D61DD054),
TMD6Word($C02DE931A83E60A9), TMD6Word($C05A1262705881F3),
TMD6Word($C0A426C4C0B18247), TMD6Word($C1484F098142868F),
TMD6Word($C390DC1202858B9F), TMD6Word($C4317824050E9CBF),
TMD6Word($C873B0480E19B5DF), TMD6Word($D0F6E0901832EE3F),
TMD6Word($F1FD01A03045125F), TMD6Word($92EB03C0408F26BF),
TMD6Word($37D70500811B4BDF), TMD6Word($5CBF0A010237DC3E),
TMD6Word($E96F1603044A745C), TMD6Word($B3DF2E070C94ACB9),
TMD6Word($54AF5E0F1D2DD5D3), TMD6Word($F95FFE1F3E7E6E26),
TMD6Word($83AE3E3F58D8926D), TMD6Word($045C7E7FB1B1A6FB),
TMD6Word($08A8BEFE4342CB56), TMD6Word($1151FF7C86855DAC),
TMD6Word($33B23CF9090FF6F8), TMD6Word($54747973121A2B50),
TMD6Word($F8F8B2E724345DA0), TMD6Word($81E1E74F6C4CF6E1),
TMD6Word($02C20C9FFC9D2B63), TMD6Word($078419BEDD3F5DE6),
TMD6Word($0C0833FDBE5BF66C), TMD6Word($1810657A58B62AF8),
TMD6Word($20308AF4B1485F50), TMD6Word($607197694290F1A0),
TMD6Word($A0F2ACD3852122E0), TMD6Word($61F5D9260E634761),
TMD6Word($A2FA724C18E7C9E2), TMD6Word($67E4A69831EA5A65),
TMD6Word($ACC9CFB043F4FEEA), TMD6Word($79925DE087CD3375),
TMD6Word($8234FB410B9F65CA), TMD6Word($06793483173B8E15),
TMD6Word($0EE369872A56922A), TMD6Word($1FC7938F74A9A674),
TMD6Word($2C8EA59FCD72CAC8), TMD6Word($791DCBBE9EC55F10),
TMD6Word($832A55FD398FF120), TMD6Word($0554EB7B531A2361),
TMD6Word($0BB914F7A63445E2), TMD6Word($1463296E684CCE64),
TMD6Word($38C752DCF09D52E8), TMD6Word($418FE739C13FE770),
TMD6Word($C21E0C72825A09C0), TMD6Word($C62C18E504B41A01),
TMD6Word($CE58314B0D4C3E03), TMD6Word($DEA062971E9C7207),
TMD6Word($EF4087AF393CA60F), TMD6Word($BD818DDF525DCA1F),
TMD6Word($4A029B3FA4BE5E3F), TMD6Word($D605B47E6D58F25E),
TMD6Word($FE0AE8FCFEB126BD), TMD6Word($8E151179D9434BDB),
TMD6Word($1E3B22F2B287DC37), TMD6Word($2E674765450A744E),
TMD6Word($7ECFCCCB8E14AC9C), TMD6Word($8F9E5916182DD5B8),
TMD6Word($1C2CF22C307E6ED1), TMD6Word($2859265840D89322));
// tap positions
MD6_TAP: array[0..4] of Integer = (17,18,21,31,67);
// right shifts
MD6_SHIFT_R: array[0..15] of Integer = (
10, 5, 13, 10, 11, 12, 2, 7, 14, 15, 7, 13, 11, 7, 6, 12);
// left shifts
MD6_SHIFT_L: array[0..15] of Integer = (
11, 24, 9, 16, 15, 9, 27, 15, 6, 2, 29, 8, 15, 5, 31, 9);
*)
{===============================================================================
TMD6ProcessorBase - class declaration
===============================================================================}
type
TMD6ProcessorBase = class(TCustomObject)
protected
// hash inputs
fHashBits: Integer;
fKey: TMD6Key;
fProcessedKey: array[0..Pred(MD6_KEY_MAXLEN)] of TMD6Word;
fRounds: Integer;
fModeControl: Integer;
// hash outputs
fMD6: TMD6;
// getters, setters
procedure SetHashBits(Value: Integer); virtual;
procedure SetKey(const Value: TMD6Key); virtual;
Function GetMD6: TMD6; virtual;
// object init/final
procedure Initialize; overload; virtual;
procedure Initialize(Source: TMD6ProcessorBase); overload; virtual;
procedure Finalize; virtual;
// hash processing
Function BuildControlWord(PaddingBits: Integer; FinalBlock: Boolean): TMD6Word; virtual;
Function BuildUniqueNodeIDWord(LevelNumber: Integer; BlockIndex: Int64): TMD6Word; virtual;
procedure CalculateBlockChunks(BlockArray: TMD6BlockArray; out BlockChunks: TMD6BlockChunks); virtual;
procedure InitializeBlockArray(out BlockArray: TMD6BlockArray; out BlockChunks: TMD6BlockChunks); virtual;
procedure CompressBlockArray(var BlockArray: TMD6BlockArray); virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TMD6ProcessorBase);
destructor Destroy; override;
// main processing
procedure ProcessInit; virtual; abstract;
procedure ProcessUpdate(const Chunk{128-byte chunk}); virtual; abstract;
procedure ProcessLast(ChunkPadBytes: TMemSize); virtual; abstract;
procedure ProcessEnd; virtual; abstract;
procedure ProcessTerminate; virtual; abstract;
// properties
property HashBits: Integer write SetHashBits;
property Key: TMD6Key write SetKey;
property Rounds: Integer write fRounds;
property ModeControl: Integer write fModeControl;
property MD6: TMD6 read GetMD6;
end;
TMD6ProcessorClass = class of TMD6ProcessorBase;
{===============================================================================
TMD6ProcessorBase - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TMD6ProcessorBase - protected methods
-------------------------------------------------------------------------------}
procedure TMD6ProcessorBase.SetHashBits(Value: Integer);
begin
fHashBits := Value;
// prepare resulting hash accordingly
SetLength(fMD6,fHashBits div 8);
end;
//------------------------------------------------------------------------------
procedure TMD6ProcessorBase.SetKey(const Value: TMD6Key);
begin
fKey := Copy(Value);
// prepare processed key
FillChar(fProcessedKey,SizeOf(fProcessedKey),0);