forked from JackTrapper/argon2-for-delphi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArgon2.pas
2204 lines (1850 loc) · 65.3 KB
/
Argon2.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 Argon2;
{
https://tools.ietf.org/html/draft-irtf-cfrg-argon2-03
}
{$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
TArgon2 = class(TObject)
private
FMemorySizeKB: Integer;
FDegreeOfParallelism: Integer;
FIterations: Integer;
FSalt: TBytes;
FKnownSecret: TBytes;
FAssociatedData: TBytes;
class function StringToUtf8(Source: UnicodeString): TBytes;
class function PasswordStringPrep(Source: UnicodeString): UnicodeString;
procedure Burn;
protected
FHashType: Cardinal; //0=Argon2d, 1=Argon2i, 2=Argon2id
function GenerateSeedBlock(const Passphrase; PassphraseLength, DesiredNumberOfBytes: Integer): TBytes;
function GenerateInitialBlock(const H0: TBytes; ColumnIndex, LaneIndex: Integer): TBytes;
function GenerateSalt: TBytes;
//Utility functions
class procedure BurnBytes(var data: TBytes);
class procedure BurnString(var s: UnicodeString);
class function PasswordToBytes(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;
class function GenRandomBytes(len: Integer; const data: Pointer): HRESULT;
class function Hash(const Buffer; BufferLen: Integer; DigestSize: Cardinal): TBytes;
class function UnicodeStringToUtf8(const Source: UnicodeString): TBytes;
class function TimingSafeSameString(const Safe, User: string): Boolean;
//The main Argon2 alorithm
function DeriveBytes(const Passphrase; PassphraseLength: Integer; DesiredNumberOfBytes: Integer): TBytes;
procedure GetBlockIndexes(i, j: Integer; out iRef, jRef: Integer); virtual; //implementation depends if you're using 2i, 2d, or 2id
procedure GetDefaultParameters(out Iterations, MemoryFactor, Parallelism: Integer);
function TryParseHashString(HashString: string; out Algorithm: string; out Version, Iterations, MemoryFactor, Parallelism: Integer; out Salt: TBytes; out Data: TBytes): Boolean;
function FormatPasswordHash(const Algorithm: string; Version: Integer; const Iterations, MemorySizeKB, Parallelism: Integer; const Salt, DerivedBytes: array of Byte): string;
class function CreateHash(AlgorithmName: string; cbHashLen: Integer; const Key; const cbKeyLen: Integer): IUnknown;
public
constructor Create;
destructor Destroy; override;
//Get a number of bytes using the default Cost, Parallelization, and Memory factors
class function GetBytes(const Passphrase; PassphraseLength: Integer; DesiredNumberOfBytes: Integer): TBytes; overload;
//Get a number of bytes, specifying the desired cost, parallelization, and memory factor
class function GetBytes(const Passphrase; PassphraseLength: Integer; const Salt: TBytes; Iterations, MemorySizeKB, Parallelism: Integer; DesiredNumberOfBytes: Integer): TBytes; overload;
//Hashes a password into the standard Argon2 OpenBSD password-file format
class function HashPassword(const Password: UnicodeString): string; overload;
class function HashPassword(const Password: UnicodeString; const Iterations, MemorySizeKB, Parallelism: Integer): string; overload;
class function CheckPassword(const Password: UnicodeString; const ExpectedHashString: string; out PasswordRehashNeeded: Boolean): Boolean; overload;
property Iterations: Integer read FIterations write FIterations; //must be at least 1 iteration
property MemorySizeKB: Integer read FMemorySizeKB write FMemorySizeKB; //must be at least 4 KB
property DegreeOfParallelism: Integer read FDegreeOfParallelism write FDegreeOfParallelism; //must be at least 1 thread
property Salt: TBytes read FSalt write FSalt;
property KnownSecret: TBytes read FKnownSecret write FKnownSecret;
property AssociatedData: TBytes read FAssociatedData write FAssociatedData;
class function CreateObject(ObjectName: string): IUnknown;
end;
{
Argon2id variant is the current recommended variant.
It was created after the original 2i and 2d variants, and combines the speed and security of both.
}
TArgon2id = TArgon2; //The base Argon2 *is* Argon2id. We just want people to fall into a pit of success.
{
Argon2i variant is resistant to side-channel attacks (i.e. mixing in Independant of the passphrase),
but is weaker than 2i.
Recommended to use Argon2id instead.
}
TArgon2i = class(TArgon2)
protected
procedure GetBlockIndexes(i, j: Integer; out iRef, jRef: Integer); override; //implementation depends if you're using 2i, 2d, or 2id
public
constructor Create;
end;
{
Argon2d variant is vulnerable to side-channel attacks (i.e. mixing is Dependant on the passphrase),
but it is stronger. It can be used for cryptocurrency, but not for passphrases.
Recommended to use Argon2id instead.
}
TArgon2d = class(TArgon2)
protected
procedure GetBlockIndexes(i, j: Integer; out iRef, jRef: Integer); override; //implementation depends if you're using 2i, 2d, or 2id
public
constructor Create;
end;
//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;
function ROR64(const Value: Int64; const n: Integer): Int64; //rotate right
implementation
{$IFDEF UnitTests}
{$DEFINE Argon2UnitTests}
{$ENDIF}
{$IFDEF NoArgon2UnitTests}
{$UNDEF Argon2UnitTests}
{$ENDIF}
uses
Classes,
{$IFDEF Argon2UnitTests}Argon2Tests,{$ENDIF}
{$IFDEF MSWINDOWS}Windows, ComObj, ActiveX,{$ENDIF}
Math;
const
ARGON_VERSION: Cardinal = $13;
// WinNls.h line 175
// String Flags.
//
LINGUISTIC_IGNORECASE = $00000010; // linguistically appropriate 'ignore case'
LINGUISTIC_IGNOREDIACRITIC = $00000020; // linguistically appropriate 'ignore nonspace'
NORM_LINGUISTIC_CASING = $08000000; // use linguistic rules for casing
{$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;
{$ENDIF}
type
EArgon2Exception = class(Exception);
HCRYPTPROV = THandle;
function StartsWith(s: string; StartingText: string): Boolean;
var
len: Integer;
begin
Result := False;
len := Length(StartingText);
if Length(s) < len then
Exit;
Result := (CompareString(LOCALE_INVARIANT, LINGUISTIC_IGNORECASE, PChar(s), len, PChar(StartingText), len) = CSTR_EQUAL);
end;
function CryptAcquireContextW(out phProv: HCRYPTPROV; pszContainer: PWideChar; pszProvider: PWideChar; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall; external advapi32;
function CryptReleaseContext(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL; stdcall; external advapi32;
function CryptGenRandom(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: Pointer): BOOL; stdcall; external advapi32;
type
UInt64Rec = packed record
case Byte of
0: (Lo, Hi: Cardinal;);
1: (Value: UInt64;);
end;
PUInt64Rec = ^UInt64Rec;
type
TBlake2bBlockArray = array[0..15] of UInt64; //operates a lot on things that are 16 "words" long (where a word in Blake2b is 64-bit)
PBlake2bBlockArray = ^TBlake2bBlockArray;
{ TBlake2b }
type
TBlake2b = class(TInterfacedObject, IHashAlgorithm)
private
protected
FDigestSize: Integer;
FKey: TBytes;
FInitialized: Boolean;
h: array[0..7] of Int64; //State vector
FBuffer: array[0..127] of Byte;
FBufferLength: Integer;
FProcessed: Int64;
procedure Burn;
procedure BlakeCompress(const m: PBlake2bBlockArray; cbBytesProcessed: Int64; IsFinalBlock: Boolean); virtual;
procedure BlakeMix(var Va, Vb, Vc, Vd: UInt64; const x, y: Int64); inline;
procedure Initialize;
public
constructor Create(const Key; cbKeyLen: Integer; cbHashLen: Integer);
destructor Destroy; override;
function GetBlockSize: Integer;
function GetDigestSize: Integer;
{ IHashAlgorithm }
procedure HashData(const Buffer; BufferLen: Integer); overload;
function Finalize: TBytes;
{ Properties }
property BlockSize: Integer read GetBlockSize;
property DigestSize: Integer read GetDigestSize;
end;
//92 MB/s (verses 22 MB/s of safe version)
TBlake2bOptimized = class(TBlake2b)
protected
procedure BlakeCompress(const m: PBlake2bBlockArray; cbBytesProcessed: Int64; IsFinalBlock: Boolean); override;
end;
TArgon2HashPrime = class(TInterfacedObject, IHashAlgorithm)
private
FDigestSize: Integer;
FBlake2: IHashAlgorithm;
protected
function GetBlockSize: Integer;
function GetDigestSize: Integer;
public
constructor Create(DigestSize: Integer);
{ Methods }
procedure HashData(const Buffer; BufferLen: Integer);
function Finalize: TBytes;
{ Properties }
property BlockSize: Integer read GetBlockSize;
property DigestSize: Integer read GetDigestSize;
end;
{ TArgon2 }
class function TArgon2.Base64Decode(const s: string): TBytes;
const
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_____
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 EArgon2Exception.Create('Invalid base64 hash string');
c1 := Char64(s[i ]);
c2 := Char64(s[i+1]);
c3 := -1;
c4 := -1;
if (i+2) <= len then
begin
c3 := Char64(s[i+2]);
if (i+3) <= len then
c4 := Char64(s[i+3]);
end;
Inc(i, 4);
if (c1 = -1) or (c2 = -1) then
raise EArgon2Exception.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 TArgon2.Base64Encode(const data: array of Byte): string;
const
Base64EncodeTable: array[0..63] of Char =
{ 0:} 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'+
{26:} 'abcdefghijklmnopqrstuvwxyz'+
{52:} '0123456789+/';
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;
procedure TArgon2.Burn;
begin
{
Destructor itself will perform a Burn.
But for the paranoid, or object reuse, we expose it.
Intentional design decision was that Password is never stored; only passed into the functions that need it.
But we do have advanced users who have Salt, Associated Data, and Known Secret.
And while Salt doesn't need to be kept secret for security purposes, Known Secret does.
}
FMemorySizeKB := 128*1024; //128 MB
FHashType := 2; //0=Argon2d, 1=Argon2i, 2=Argon2id
FDegreeOfParallelism := 1; //1 thread
FIterations := 1000; //1000 iterations
TArgon2.BurnBytes(FSalt);
TArgon2.BurnBytes(FAssociatedData);
TArgon2.BurnBytes(FKnownSecret);
end;
class procedure TArgon2.BurnBytes(var data: TBytes);
begin
if Length(data) <= 0 then
Exit;
FillChar(data[Low(data)], Length(data), 0);
SetLength(data, 0);
end;
class procedure TArgon2.BurnString(var s: UnicodeString);
begin
if Length(s) > 0 then
begin
UniqueString({var}s); //We can't FillChar the string if it's shared, or its in the constant data page
FillChar(s[1], Length(s), 0);
s := '';
end;
end;
const
//The Blake2 IV comes from the SHA2-512 IV.
//The values are the the fractional part of the square root of the first 8 primes (2, 3, 5, 7, 11, 13, 17, 19)
IV: array[0..7] of Int64 = (
Int64($6A09E667F3BCC908), //frac(sqrt(2))
Int64($BB67AE8584CAA73B), //frac(sqrt(3))
Int64($3C6EF372FE94F82B), //frac(sqrt(5))
Int64($A54FF53A5F1D36F1), //frac(sqrt(7))
Int64($510E527FADE682D1), //frac(sqrt(11))
Int64($9B05688C2B3E6C1F), //frac(sqrt(13))
Int64($1F83D9ABFB41BD6B), //frac(sqrt(17))
Int64($5BE0CD19137E2179) //frac(sqrt(19))
);
SIGMA: array[0..9] of array[0..15] of Integer = (
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
(14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3),
(11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4),
( 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8),
( 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13),
( 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9),
(12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11),
(13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10),
( 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5),
(10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0)
);
class function TArgon2.CheckPassword(const Password: UnicodeString; const ExpectedHashString: string; out PasswordRehashNeeded: Boolean): Boolean;
var
ar: TArgon2;
algorithm: string;
passwordUtf8: TBytes;
version, iterations, memorySizeKB, parallelism: Integer;
salt, expected, actual: TBytes;
t1, t2, freq: Int64;
duration: Real;
begin
Result := False;
PasswordRehashNeeded := False;
ar := TArgon2.Create;
try
if not ar.TryParseHashString(ExpectedHashString, {out}algorithm, {out}version, {out}iterations, {out}memorySizeKB, {out}parallelism, {out}salt, {out}expected) then
raise EArgon2Exception.Create('Could not parse password hash string');
try
passwordUtf8 := TArgon2.PasswordToBytes(Password);
QueryPerformanceCounter(t1);
actual := TArgon2.GetBytes(passwordUtf8, Length(Password)*SizeOf(WideChar), salt, iterations, memorySizeKB, parallelism, 32);
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
begin
duration := (t2-t1)/freq * 1000; //ms
if duration < 250 then
PasswordRehashNeeded := True;
end;
end;
finally
ar.BurnBytes(actual);
ar.BurnBytes(expected);
ar.BurnBytes({var}passwordUtf8);
end;
finally
ar.Free;
end;
end;
constructor TArgon2.Create;
begin
inherited Create;
FMemorySizeKB := 128*1024; //128 MB
FHashType := 2; //0=Argon2d, 1=Argon2i, 2=Argon2id
FDegreeOfParallelism := 1; //1 thread
FIterations := 1000; //1000 iterations
SetLength(FSalt, 0); //we can't generate salt for them; they need to know what it was
SetLength(FAssociatedData, 0);
SetLength(FKnownSecret, 0);
end;
class function TArgon2.CreateHash(AlgorithmName: string; cbHashLen: Integer; const Key; const cbKeyLen: Integer): IUnknown;
begin
if AlgorithmName = 'Blake2b.Optimized' then
Result := TBlake2bOptimized.Create(Key, cbKeyLen, cbHashLen)
else if AlgorithmName = 'Blake2b.Safe' then
Result := TBlake2b.Create(Key, cbKeyLen, cbHashLen)
else if AlgorithmName = 'Blake2b' then
Result := TArgon2.CreateHash('Blake2b.Optimized', cbHashLen, Key, cbKeyLen)
else
raise EArgon2Exception.CreateFmt('Unknown hash algorithmname "%s"', [AlgorithmName]);
end;
class function TArgon2.CreateObject(ObjectName: string): IUnknown;
begin
if ObjectName = 'Blake2b' then
Result := TArgon2.CreateObject('Blake2b.Optimized')
else if ObjectName = 'Blake2b.Safe' then
Result := TBlake2b.Create(Pointer(nil)^, 0, 64)
else if ObjectName = 'Blake2b.Optimized' then
Result := TBlake2bOptimized.Create(Pointer(nil)^, 0, 64)
else
raise EArgon2Exception.CreateFmt('Unknown object name "%s"', [ObjectName]);
end;
procedure TArgon2.GetBlockIndexes(i, j: Integer; out iRef, jRef: Integer);
begin
{
We are Argon2id.
}
//Since i cannot make heads nor tails of either their PDF, their RFC, their GitHub, nor their sample code, this is a todo
iRef := 0;
jRef := 0;
raise ENotImplemented.Create('Someone needs to figure out the 2id block schedule alorithm');
end;
class function TArgon2.GetBytes(const Passphrase; PassphraseLength: Integer; const Salt: TBytes; Iterations, MemorySizeKB, Parallelism: Integer; DesiredNumberOfBytes: Integer): TBytes;
var
ar: TArgon2;
begin
{
Iterations (t): Number of iterations
Used to determine the running time independantly of the memory size
1 - 0x7FFFFFFF
Parallelism (p): Degree of Parallelism
Determines how many independant (but synchronizing) computational chains can be run.
1 - 0x00FFFFFF
MemorySizeKB (m): number of kilobyes
8p - 0x7FFFFFFF
Secret value (K): Serves as a key if necessary
0 - 32 bytes
}
//Unhelpfully, Argon2 doesn't
ar := TArgon2.Create();
try
ar.Iterations := Iterations;
ar.MemorySizeKB := MemorySizeKB;
ar.DegreeOfParallelism := Parallelism;
ar.Salt := Salt;
Result := ar.DeriveBytes(Passphrase, PassphraseLength, DesiredNumberOfBytes);
finally
ar.Free;
end;
end;
function TArgon2.FormatPasswordHash(const Algorithm: string; Version: Integer;
const Iterations, MemorySizeKB, Parallelism: Integer; const Salt, DerivedBytes: array of Byte): string;
var
saltString: string;
hashString: string;
begin
{
Type: Argon2i
Version: 19
Iterations: 2
MemorySizeKB: 65536 = 65536 KB
Parallelism: 4
Salt: 736F6D6573616c74
Hash: 45d7ac72e76f242b20b77b9bf9bf9d5915894e669a24e6c6
Result: $argon2i$v=19$m=65536,t=2,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG
}
saltString := Base64Encode(Salt);
hashString := Base64Encode(DerivedBytes);
Result := Format('$%s$v=%d$m=%d,t=%d,p=%d$%s$%s', [
Algorithm, //"argon2i", "argon2d", "argon2id"
Version, //19 (optional)
MemorySizeKB, //65535 KB
Iterations, //1 iterations
Parallelism, //4 threads
saltString, //"c29tZXNhbHQ"
hashString //"RdescudvJCsgt3ub+b+dWRWJTmaaJObG"
]);
end;
function TArgon2.GenerateSalt: TBytes;
var
type4Uuid: TGUID;
salt: TBytes;
const
ARGON2_SALT_LEN = 16; //Salt is a 128-bit (16 byte) random value
begin
SetLength(salt, ARGON2_SALT_LEN);
//Use real random data. Fallback to random guid if it fails
if Failed(Self.GenRandomBytes(ARGON2_SALT_LEN, {out}@salt[0])) then
begin
//Type 4 UUID (RFC 4122) is a handy source of (almost) 128-bits of random data (actually 120 bits)
//But the security doesn't come from the salt being secret, it comes from the salt being different each time
OleCheck(CoCreateGUID(Type4Uuid));
Move(type4Uuid.D1, salt[0], ARGON2_SALT_LEN); //16 bytes
end;
Result := salt;
end;
class function TArgon2.GenRandomBytes(len: Integer; const data: Pointer): HRESULT;
var
hProv: THandle;
const
PROV_RSA_FULL = 1;
CRYPT_VERIFYCONTEXT = DWORD($F0000000);
CRYPT_SILENT = $00000040;
begin
if not CryptAcquireContextW(hPRov, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_SILENT) then
begin
Result := HResultFromWin32(GetLastError);
Exit;
end;
try
if not CryptGenRandom(hProv, len, data) then
begin
Result := HResultFromWin32(GetLastError);
Exit;
end;
finally
CryptReleaseContext(hProv, 0);
end;
Result := S_OK;
end;
type
TLane = class(TObject)
public
BlockCount: Integer;
end;
function TArgon2.DeriveBytes(const Passphrase; PassphraseLength: Integer; DesiredNumberOfBytes: Integer): TBytes;
var
lanes: array of TArray<UInt64>;
i, j: Integer;
iref, jref: Integer;
digest: TBytes;
h0: TBytes;
columnCount: Integer;
bFinal: TBytes;
lastColumnIndex: Integer;
nIteration: Integer;
const
SDesiredBytesMaxError = 'Argon2 only supports generating a maximum of 1,024 bytes (Requested %d bytes)';
SInvalidIterations = 'Argon2 hash requires at least 1 iteration (Requested %d)';
SInvalidMemorySize = 'Argon2 requires at least 4 KB to be used (Requested %d KB)';
SInvalidParallelism = 'Argon2 requires at one 1 thread (Requested %d parallelism)';
BlockStride = 128;
begin
if DesiredNumberOfBytes > 1024 then
raise EArgon2Exception.CreateFmt(SDesiredBytesMaxError, [DesiredNumberOfBytes]);
if FIterations < 1 then
raise EArgon2Exception.CreateFmt(SInvalidIterations, [FIterations]);
if FMemorySizeKB < 4 then
raise EArgon2Exception.CreateFmt(SInvalidMemorySize, [FMemorySizeKB]);
if FDegreeOfParallelism < 1 then
raise EArgon2Exception.CreateFmt(SInvalidParallelism, [FDegreeOfParallelism]);
//Generate the initial 64-byte block h0
h0 := Self.GenerateSeedBlock(Passphrase, PassphraseLength, DesiredNumberOfBytes);
//Calculate number of 1 KiB blocks by rounding down memorySizeKB to the nearest multiple of 4*DegreeOfParallelism kilobytes
columnCount := memorySizeKB div 4 div FDegreeOfParallelism;
//Allocate two-dimensional array of 1 KiB blocks (parallelism rows x columnCount columns)
SetLength(lanes, FDegreeOfParallelism);
for i := 0 to FDegreeOfParallelism-1 do
SetLength(lanes[i], columnCount*1024 div SizeOf(UInt64));
//Compute the first and second blocks of each lane (i.e. column zero and one)
for i := 0 to FDegreeOfParallelism-1 do
begin
//lanes[i][0] := Hash(H0 || 0 || i);
digest := GenerateInitialBlock(h0, 0, i);
Move(digest[0], lanes[i][0], 1024);
//lanes[i][1] := Hash(H0 || 1 || i);
GenerateInitialBlock(h0, 1, i);
Move(digest[0], lanes[i][BlockStride], 1024);
end;
//Compute remaining columns of each lane
for i := 0 to FDegreeOfParallelism-1 do //for each row
begin
for j := 2 to columnCount-1 do //for each subsequent column
begin
//iref and jref indexes depend if it's Argon2i, Argon2d, or Argon2id (See section 3.4)
Self.GetBlockIndexes(i, j, {out}iref, {out}jref);
//TODO: They don't document what the function G is
//B[i][j] = G(B[i][j-1], B[iref][jref])
end;
end;
//Further passes when iterations > 1
for nIteration := 2 to Iterations do
begin
for i := 1 to FDegreeOfParallelism-1 do //for each row
begin
for j := 2 to columnCount-1 do //for each subsequent column
begin
//iref and jref indexes depend if it's Argon2i, Argon2d, or Argon2id (See section 3.4)
Self.GetBlockIndexes(i, j, {out}iref, {out}jref);
//TODO: They don't document what the function G is
//B[i][0] = G(B[i][columnCount-1], B[iref][jref])
//B[i][j] = G(B[i][j-1], B[iref][jref])
end;
end;
end;
//The final block is the xor of the last column of each row
//bFinal := b[0][lastColumn] || b[1][lastColumn] || .. || b[FDegreeOfParallelism-1][lastColumn]
SetLength(bFinal, 1024);
lastColumnIndex := (columnCount-1)*BlockStride;
Move(lanes[0][lastColumnIndex], bFinal[0], 1024);
for i := 1 to FDegreeOfParallelism-1 do //for each row
begin
for j := 0 to 1024-1 do
bFinal[j] := bFinal[j] xor lanes[i][lastColumnIndex+j];
end;
Result := Hash(bFinal[0], 1024, DesiredNumberOfBytes);
end;
destructor TArgon2.Destroy;
begin
Self.Burn;
inherited;
end;
function TArgon2.GenerateInitialBlock(const H0: TBytes; ColumnIndex, LaneIndex: Integer): TBytes;
var
hash: IHashAlgorithm;
begin
hash := TArgon2HashPrime.Create(1024);
//block = Hash( h0 || columnIndex || LaneIndex, 1024);
hash.HashData(h0[0], Length(h0));
hash.HashData(ColumnIndex, 4);
hash.HashData(LaneIndex, 4);
Result := hash.Finalize;
end;
function TArgon2.GenerateSeedBlock(const Passphrase; PassphraseLength: Integer; DesiredNumberOfBytes: Integer): TBytes;
var
blake2b: IHashAlgorithm;
n: Integer;
begin
{
Generate the 64-byte H0 seed block
}
blake2b := Self.CreateObject('Blake2b') as IHashAlgorithm;
blake2b.HashData(FDegreeOfParallelism, 4);
blake2b.HashData(DesiredNumberOfBytes, 4);
blake2b.HashData(FMemorySizeKB, 4);
blake2b.HashData(FIterations, 4);
blake2b.HashData(Cardinal(ARGON_VERSION), 4);
blake2b.HashData(FHashType, 4);
//Variable length items are prepended with their length
blake2b.HashData(PassphraseLength, 4);
blake2b.HashData(Passphrase, PassphraseLength);
n := Length(FSalt);
blake2b.HashData(n, 4);
blake2b.HashData(PByte(FSalt)^, Length(FSalt));
n := Length(FKnownSecret);
blake2b.HashData(n, 4);
blake2b.HashData(PByte(FKnownSecret)^, Length(FKnownSecret));
n := Length(FAssociatedData);
blake2b.HashData(n, 4);
blake2b.HashData(PByte(FAssociatedData)^, Length(FAssociatedData));
Result := blake2b.Finalize;
end;
class function TArgon2.GetBytes(const Passphrase; PassphraseLength, DesiredNumberOfBytes: Integer): TBytes;
var
ar: TArgon2;
begin
{
Iterations (t): Number of iterations
Used to determine the running time independantly of the memory size
1 - 0x7FFFFFFF
Parallelism (p): Degree of Parallelism
Determines how many independant (but synchronizing) computational chains can be run.
1 - 0x00FFFFFF
MemorySizeKB (m): number of kilobyes
8p - 0x7FFFFFFF
Secret value (K): Serves as a key if necessary
0 - 32 bytes
}
//Unhelpfully, Argon2 doesn't
ar := TArgon2.Create();
try
Result := ar.DeriveBytes(Passphrase, PassphraseLength, DesiredNumberOfBytes);
finally
ar.Free;
end;
end;
procedure TArgon2.GetDefaultParameters(out Iterations, MemoryFactor, Parallelism: Integer);
begin
end;
class function TArgon2.HashPassword(const Password: UnicodeString): string;
var
iterations, memorySizeKB, degreeOfParallelism: Integer;
begin
iterations := 10000; // 10,000 iterations
memorySizeKB := 128*1024; // 128 MB
degreeOfParallelism := 1; // 1 thread
Result := TArgon2.HashPassword(Password, iterations, memorySizeKB, degreeOfParallelism);
end;
class function TArgon2.Hash(const Buffer; BufferLen: Integer; DigestSize: Cardinal): TBytes;
var
blake2b: IHashAlgorithm;
digest: TBytes;
begin
{
This is a variable length hash function, that can generate digests up to 2^32 bytes.
}
if DigestSize <= 64 then
begin
blake2b := Self.CreateObject('Blake2b') as IHashAlgorithm;
blake2b.HashData(Buffer, BufferLen);
Result := blake2b.Finalize;
if DigestSize < 64 then
begin
//Grab first DigestSize bytes
SetLength(digest, DigestSize);
Move(Result[0], digest[0], DigestSize);
Result := digest;
end;
Exit;
end;
raise ENotImplemented.Create('todo: digests over 64-bytes');
//For desired digest sizes over 64 bytes, we generate a series of 64-byte blocks, and use the first 32-bytes from each
//Number of whole blocks (knowing we're going to only use 32-bytes from each)
end;
class function TArgon2.HashPassword(const Password: UnicodeString; const Iterations, MemorySizeKB, Parallelism: Integer): string;
var
salt, derivedBytes: TBytes;
utf8Password: TBytes;
ar: TArgon2;
begin
{
Iterations (t): Number of iterations
Used to determine the running time independantly of the memory size
1 - 0x7FFFFFFF
Parallelism (p): Degree of Parallelism
Determines how many independant (but synchronizing) computational chains can be run.
1 - 0x00FFFFFF
MemorySizeKB (m): power of two number of kilobyes (minimum of 8*Parallelism KB)
8p - 0x7FFFFFFF
}
if MemorySizeKB < (8*Parallelism) then
raise EArgon2Exception.CreateFmt('Requested MemorySizeKB (%d) is to small to handle desired Parallelism (%d)', [MemorySizeKB, Parallelism]);
ar := TArgon2.Create;
try
salt := ar.GenerateSalt;
utf8Password := TArgon2.PasswordToBytes(Password); //use proper normalization Form C, convert all spaces, utf8 encoding
try
derivedBytes := TArgon2.GetBytes(utf8Password, Length(Password)*SizeOf(WideChar), salt, Iterations, MemorySizeKB, Parallelism, 32);
finally
TArgon2.BurnBytes({var}utf8Password);