Debian Codegraph @

components/kascrypt/Hashes/argon2.pas

raw
1 {
2 /*
3 * Argon2 reference source code package - reference C implementations
4 *
5 * Copyright 2015
6 * Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
7 *
8 * Pascal tranlastion in 2018 by Alexander Koblov ([email protected])
9 *
10 * You may use this work under the terms of a Creative Commons CC0 1.0
11 * License/Waiver or the Apache Public License 2.0, at your option. The terms of
12 * these licenses can be found at:
13 *
14 * - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
15 * - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * You should have received a copy of both of these licenses along with this
18 * software. If not, they may be obtained at the above URLs.
19 */
20 }
21
22 unit Argon2;
23
24 {$mode objfpc}{$H+}
25 {$define USE_MTPROCS}
26 {.$define GENKAT}
27
28 interface
29
30 uses
31 CTypes, DCblake2;
32
33 const
34 //* Number of synchronization points between lanes per pass */
35 ARGON2_SYNC_POINTS = cuint32(4);
36
37 //* Flags to determine which fields are securely wiped (default = no wipe). */
38 ARGON2_DEFAULT_FLAGS = cuint32(0);
39 ARGON2_FLAG_CLEAR_PASSWORD = (cuint32(1) shl 0);
40 ARGON2_FLAG_CLEAR_SECRET = (cuint32(1) shl 1);
41
42 const
43 //* Error codes */
44 ARGON2_OK = 0;
45 ARGON2_MEMORY_ALLOCATION_ERROR = -22;
46 ARGON2_INCORRECT_PARAMETER = -25;
47
48
49 type
50 Pargon2_context = ^Targon2_context;
51 Targon2_context = record
52 out_: pcuint8; //* output array */
53 outlen: cuint32; //* digest length */
54
55 pwd: pcuint8; //* password array */
56 pwdlen: cuint32; //* password length */
57
58 salt: pcuint8; //* salt array */
59 saltlen: cuint32; //* salt length */
60
61 secret: pcuint8; //* key array */
62 secretlen: cuint32; //* key length */
63
64 ad: pcuint8; //* associated data array */
65 adlen: cuint32; //* associated data length */
66
67 t_cost: cuint32; //* number of passes */
68 m_cost: cuint32; //* amount of memory requested (KB) */
69 lanes: cuint32; //* number of lanes */
70 threads: cuint32; //* maximum number of threads */
71
72 version: cuint32; //* version number */
73
74 flags: cuint32; //* array of bool options */
75 end;
76
77 //* Argon2 primitive type */
78 Targon2_type = (
79 Argon2_d = 0,
80 Argon2_i = 1,
81 Argon2_id = 2
82 );
83
84 //* Version of the algorithm */
85 Targon2_version = (
86 ARGON2_VERSION_10 = $10,
87 ARGON2_VERSION_13 = $13,
88 ARGON2_VERSION_NUMBER = ARGON2_VERSION_13
89 );
90
91 function argon2id_kdf(const t_cost, m_cost, parallelism: cuint32;
92 const pwd: pansichar; const pwdlen: csize_t;
93 const salt: pansichar; const saltlen: csize_t;
94 hash: Pointer; const hashlen: csize_t): cint;
95
96 function argon2_hash(const t_cost, m_cost, parallelism: cuint32;
97 const pwd: pansichar; const pwdlen: csize_t;
98 const salt: pansichar; const saltlen: csize_t;
99 const secret: pansichar; const secretlen: csize_t;
100 const ad: pansichar; const adlen: csize_t;
101 hash: Pointer; const hashlen: csize_t;
102 type_: Targon2_type; version: Targon2_version): cint;
103
104 function argon2_selftest: Boolean;
105
106 implementation
107
108 {$R-}{$Q-}
109
110 uses
111 Math, Hash, SysUtils, StrUtils
112 {$IF DEFINED(USE_MTPROCS)}
113 , MTProcs
114 {$ENDIF}
115 ;
116
117 //**********************Argon2 internal constants*******************************/
118
119 const
120 //* Memory block size in bytes */
121 ARGON2_BLOCK_SIZE = 1024;
122 ARGON2_QWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE div 8;
123
124 (* Number of pseudo-random values generated by one call to Blake in Argon2i
125 to
126 generate reference block positions *)
127 ARGON2_ADDRESSES_IN_BLOCK = 128;
128
129 //* Pre-hashing digest length and its extension*/
130 ARGON2_PREHASH_DIGEST_LENGTH = 64;
131 ARGON2_PREHASH_SEED_LENGTH = 72;
132
133 //*************************Argon2 internal data types***********************/
134 type
135 (*
136 * Structure for the (1KB) memory block implemented as 128 64-bit words.
137 * Memory blocks can be copied, XORed. Internal words can be accessed by [] (no
138 * bounds checking).
139 *)
140 Pblock = ^Tblock;
141 Tblock = packed record
142 v: packed array [0..ARGON2_QWORDS_IN_BLOCK-1] of cuint64;
143 end;
144
145 (*
146 * Argon2 instance: memory pointer, number of passes, amount of memory, type,
147 * and derived values.
148 * Used to evaluate the number and location of blocks to construct in each
149 * thread
150 *)
151 Pargon2_instance_t = ^Targon2_instance_t;
152 Targon2_instance_t = record
153 memory: Pblock; //* Memory pointer */
154 version: Targon2_version;
155 passes: cuint32; //* Number of passes */
156 memory_blocks: cuint32; //* Number of blocks in memory */
157 segment_length: cuint32;
158 lane_length: cuint32;
159 lanes: cuint32;
160 threads: cuint32;
161 type_: Targon2_type;
162 print_internals: cint; //* whether to print the memory blocks */
163 context_ptr: Pargon2_context; //* points back to original context */
164 end;
165
166 (*
167 * Argon2 position: where we construct the block right now. Used to distribute
168 * work between threads.
169 *)
170 Pargon2_position_t = ^Targon2_position_t;
171 Targon2_position_t = record
172 pass: cuint32;
173 slice: cuint8;
174 index: cuint32;
175 instance_ptr: Pargon2_instance_t;
176 end;
177
178 {$IFDEF GENKAT}
179
180 procedure initial_kat(const blockhash: pcuint8; const context: Pargon2_context;
181 type_: Targon2_type);
182 var
183 i: cuint32;
184 begin
185 if (blockhash <> nil) and (context <> nil) then
186 begin
187 WriteLn('=======================================');
188
189 WriteLn(Format('%d version number %d', [type_, context^.version]));
190
191 WriteLn('=======================================');
192
193 WriteLn(Format('Memory: %u KiB, Iterations: %u, Parallelism: %u lanes, Tag length: %u bytes',
194 [context^.m_cost, context^.t_cost, context^.lanes, context^.outlen]));
195
196 Write(Format('Password[%u]: ', [context^.pwdlen]));
197
198 if (context^.flags and ARGON2_FLAG_CLEAR_PASSWORD <> 0) then
199 begin
200 WriteLn('CLEARED');
201 end
202 else begin
203 for i := 0 to context^.pwdlen - 1 do
204 Write(Format('%2.2x ', [context^.pwd[i]]));
205 WriteLn;
206 end;
207
208 Write(Format('Salt[%u]: ', [context^.saltlen]));
209
210 for i := 0 to context^.saltlen - 1 do begin
211 Write(Format('%2.2x ', [context^.salt[i]]));
212 end;
213 WriteLn;
214
215 (*
216 printf("Secret[%u]: ", context->secretlen);
217
218 if (context->flags & ARGON2_FLAG_CLEAR_SECRET) {
219 printf("CLEARED\n");
220 } else {
221 for (i = 0; i < context->secretlen; ++i) {
222 printf("%2.2x ", ((unsigned char )context->secret)[i]);
223 }
224
225 printf("\n");
226 }
227
228 printf("Associated data[%u]: ", context->adlen);
229
230 for (i = 0; i < context->adlen; ++i) {
231 printf("%2.2x ", ((unsigned char )context->ad)[i]);
232 }
233
234 printf("\n");
235
236 printf("Pre-hashing digest: ");
237
238 for (i = 0; i < ARGON2_PREHASH_DIGEST_LENGTH; ++i) {
239 printf("%2.2x ", ((unsigned char )blockhash)[i]);
240 }
241
242 printf("\n"); *)
243 end;
244 end;
245
246 procedure print_tag(const out_: pcuint8; outlen: cuint32);
247 var
248 i: cuint32;
249 begin
250 if (out_ <> nil) then
251 begin
252 Write('Tag: ');
253 for i := 0 to outlen - 1 do begin
254 Write(Format('%2.2x ', [out_[i]]));
255 end;
256 WriteLn;
257 end;
258 end;
259
260 procedure internal_kat(const instance: Pargon2_instance_t; pass: cuint32);
261 var
262 i, j: cuint32;
263 how_many_words: cuint32;
264 begin
265 if (instance <> nil) then
266 begin
267 WriteLn(Format('After pass %u:', [pass]));
268
269 for i := 0 to instance^.memory_blocks - 1 do
270 begin
271 how_many_words :=
272 IfThen(instance^.memory_blocks > ARGON2_QWORDS_IN_BLOCK,
273 1,
274 ARGON2_QWORDS_IN_BLOCK);
275
276 for j := 0 to how_many_words - 1 do
277 WriteLn(Format('Block %.4u [%3u]: %s', [i, j,
278 HexStr(instance^.memory[i].v[j], 16)]));
279 end;
280 end;
281 end;
282
283 {$ENDIF}
284
285 function load32( const src: Pointer ): cuint32; inline;
286 begin
287 Result := NtoLE(pcuint32(src)^);
288 end;
289
290 function load64( const src: pointer ): cuint64; inline;
291 begin
292 Result := NtoLE(pcuint64(src)^);
293 end;
294
295 procedure store32( dst: pointer; w: cuint32 ); inline;
296 begin
297 pcuint32(dst)^ := LEtoN(w);
298 end;
299
300 procedure store64( dst: pointer; w: cuint64 ); inline;
301 begin
302 pcuint64(dst)^ := LEtoN(w);
303 end;
304
305 //* designed by the Lyra PHC team */
306 function fBlaMka(x, y: cuint64): cuint64; inline;
307 const
308 m = cuint64($FFFFFFFF);
309 begin
310 Result:= x + y + 2 * ((x and m) * (y and m));
311 end;
312
313 procedure G(var a, b, c, d: cuint64); inline;
314 begin
315 a := fBlaMka(a, b);
316 d := RorQWord(d xor a, 32);
317 c := fBlaMka(c, d);
318 b := RorQWord(b xor c, 24);
319 a := fBlaMka(a, b);
320 d := RorQWord(d xor a, 16);
321 c := fBlaMka(c, d);
322 b := RorQWord(b xor c, 63);
323 end;
324
325 procedure BLAKE2_ROUND_NOMSG(var v0, v1, v2, v3, v4, v5, v6, v7,
326 v8, v9, v10, v11, v12, v13, v14, v15: cuint64); inline;
327 begin
328 G(v0, v4, v8, v12);
329 G(v1, v5, v9, v13);
330 G(v2, v6, v10, v14);
331 G(v3, v7, v11, v15);
332 G(v0, v5, v10, v15);
333 G(v1, v6, v11, v12);
334 G(v2, v7, v8, v13);
335 G(v3, v4, v9, v14);
336 end;
337
338 //***************Instance and Position constructors**********/
339 procedure init_block_value(b: Pblock; in_: cuint8); inline;
340 begin
341 FillChar(b^, SizeOf(Tblock), in_);
342 end;
343
344 procedure copy_block(dst: Pblock; const src: Pblock); inline;
345 begin
346 Move(src^, dst^, SizeOf(Tblock));
347 end;
348
349 procedure xor_block(dst: Pblock; const src: Pblock);
350 var
351 i: cint;
352 begin
353 for i := 0 to ARGON2_QWORDS_IN_BLOCK - 1 do
354 dst^.v[i] := dst^.v[i] xor src^.v[i];
355 end;
356
357 procedure load_block(dst: Pblock; const input: PByte); inline;
358 begin
359 Move(input^, dst^, SizeOf(Tblock));
360 end;
361
362 procedure store_block(output: PByte; const src: Pblock); inline;
363 begin
364 Move(src^, output^, SizeOf(Tblock));
365 end;
366
367 //***************Memory functions*****************/
368
369 procedure secure_wipe_memory(v: Pointer; n: csize_t);
370 {$OPTIMIZATION OFF}
371 begin
372 FillChar(v^, n, 0);
373 end;
374 {$OPTIMIZATION DEFAULT}
375
376 procedure clear_internal_memory(v: Pointer; n: csize_t);
377 begin
378 if (v <> nil) then secure_wipe_memory(v, n);
379 end;
380
381 function allocate_memory(memory: PPByte; num, size: csize_t): cint;
382 var
383 memory_size: csize_t;
384 begin
385 memory_size := num * size;
386 if (memory = nil) then begin
387 Exit(ARGON2_MEMORY_ALLOCATION_ERROR);
388 end;
389
390 //* Check for multiplication overflow */
391 if (size <> 0) and (memory_size div size <> num) then begin
392 Exit(ARGON2_MEMORY_ALLOCATION_ERROR);
393 end;
394
395 memory^ := GetMem(memory_size);
396
397 if (memory^ = nil) then begin
398 Exit(ARGON2_MEMORY_ALLOCATION_ERROR);
399 end;
400
401 Result:= ARGON2_OK;
402 end;
403
404 procedure free_memory(memory: pcuint8; num, size: csize_t);
405 var
406 memory_size: csize_t;
407 begin
408 memory_size := num * size;
409 clear_internal_memory(memory, memory_size);
410 FreeMem(memory);
411 end;
412
413 (*
414 * Function fills a new memory block and optionally XORs the old block over the new one.
415 * @next_block must be initialized.
416 * @param prev_block Pointer to the previous block
417 * @param ref_block Pointer to the reference block
418 * @param next_block Pointer to the block to be constructed
419 * @param with_xor Whether to XOR into the new block (1) or just overwrite (0)
420 * @pre all block pointers must be valid
421 *)
422 procedure fill_block(const prev_block: Pblock; const ref_block: Pblock;
423 next_block: Pblock; with_xor: boolean);
424 var
425 i: cuint32;
426 blockR, block_tmp: Tblock;
427 begin
428 copy_block(@blockR, ref_block);
429 xor_block(@blockR, prev_block);
430 copy_block(@block_tmp, @blockR);
431 //* Now blockR = ref_block + prev_block and block_tmp = ref_block + prev_block */
432 if (with_xor) then
433 begin
434 //* Saving the next block contents for XOR over: */
435 xor_block(@block_tmp, next_block);
436 (* Now blockR = ref_block + prev_block and
437 block_tmp = ref_block + prev_block + next_block *)
438 end;
439
440 (* Apply Blake2 on columns of 64-bit words: (0,1,...,15) , then
441 (16,17,..31)... finally (112,113,...127) *)
442 for i := 0 to 7 do
443 begin
444 BLAKE2_ROUND_NOMSG(
445 blockR.v[16 * i], blockR.v[16 * i + 1], blockR.v[16 * i + 2],
446 blockR.v[16 * i + 3], blockR.v[16 * i + 4], blockR.v[16 * i + 5],
447 blockR.v[16 * i + 6], blockR.v[16 * i + 7], blockR.v[16 * i + 8],
448 blockR.v[16 * i + 9], blockR.v[16 * i + 10], blockR.v[16 * i + 11],
449 blockR.v[16 * i + 12], blockR.v[16 * i + 13], blockR.v[16 * i + 14],
450 blockR.v[16 * i + 15]);
451 end;
452
453 (* Apply Blake2 on rows of 64-bit words: (0,1,16,17,...112,113), then
454 (2,3,18,19,...,114,115).. finally (14,15,30,31,...,126,127) *)
455 for i := 0 to 7 do
456 begin
457 BLAKE2_ROUND_NOMSG(
458 blockR.v[2 * i], blockR.v[2 * i + 1], blockR.v[2 * i + 16],
459 blockR.v[2 * i + 17], blockR.v[2 * i + 32], blockR.v[2 * i + 33],
460 blockR.v[2 * i + 48], blockR.v[2 * i + 49], blockR.v[2 * i + 64],
461 blockR.v[2 * i + 65], blockR.v[2 * i + 80], blockR.v[2 * i + 81],
462 blockR.v[2 * i + 96], blockR.v[2 * i + 97], blockR.v[2 * i + 112],
463 blockR.v[2 * i + 113]);
464 end;
465
466 copy_block(next_block, @block_tmp);
467 xor_block(next_block, @blockR);
468 end;
469
470 function blake2b(out_: pcuint8; outlen: csize_t; const in_: pcuint8; inlen: csize_t): cint;
471 var
472 S: blake2b_state;
473 begin
474 if (blake2b_init(@S, outlen) = 0) then
475 begin
476 blake2b_update(@S, in_, inlen);
477 blake2b_final(@S, out_, outlen);
478 Exit(0);
479 end;
480 Result:= -1;
481 end;
482
483 procedure blake2b_long(pout: pointer; outlen: csize_t; const in_: pointer; inlen: csize_t);
484 var
485 out_: pcuint8;
486 toproduce: cuint32;
487 blake_state: blake2b_state;
488 outlen_bytes: array [0..sizeof(cuint32)-1] of cuint8;
489 in_buffer: array[0..Pred(BLAKE2B_OUTBYTES)] of cuint8;
490 out_buffer: array[0..Pred(BLAKE2B_OUTBYTES)] of cuint8;
491 begin
492 out_:= pout;
493 //* Ensure little-endian byte order! */
494 store32(@outlen_bytes[0], cuint32(outlen));
495
496 if (outlen <= BLAKE2B_OUTBYTES) then
497 begin
498 blake2b_init(@blake_state, outlen);
499 blake2b_update(@blake_state, outlen_bytes, sizeof(outlen_bytes));
500 blake2b_update(@blake_state, in_, inlen);
501 blake2b_final(@blake_state, out_, outlen);
502 end
503 else begin
504 blake2b_init(@blake_state, BLAKE2B_OUTBYTES);
505 blake2b_update(@blake_state, outlen_bytes, sizeof(outlen_bytes));
506 blake2b_update(@blake_state, in_, inlen);
507 blake2b_final(@blake_state, out_buffer, BLAKE2B_OUTBYTES);
508 Move(out_buffer[0], out_^, BLAKE2B_OUTBYTES div 2);
509 out_ += BLAKE2B_OUTBYTES div 2;
510 toproduce := cuint32(outlen) - BLAKE2B_OUTBYTES div 2;
511
512 while (toproduce > BLAKE2B_OUTBYTES) do
513 begin
514 Move(out_buffer[0], in_buffer[0], BLAKE2B_OUTBYTES);
515 blake2b(out_buffer, BLAKE2B_OUTBYTES, in_buffer, BLAKE2B_OUTBYTES);
516 Move(out_buffer[0], out_^, BLAKE2B_OUTBYTES div 2);
517 out_ += BLAKE2B_OUTBYTES div 2;
518 toproduce -= BLAKE2B_OUTBYTES div 2;
519 end;
520
521 Move(out_buffer[0], in_buffer[0], BLAKE2B_OUTBYTES);
522 blake2b(out_buffer, toproduce, in_buffer, BLAKE2B_OUTBYTES);
523 Move(out_buffer[0], out_^, toproduce);
524 end;
525 clear_internal_memory(@blake_state, sizeof(blake_state));
526 end;
527
528 procedure next_addresses(address_block, input_block: Pblock;
529 const zero_block: Pblock);
530 begin
531 Inc(input_block^.v[6]);
532 fill_block(zero_block, input_block, address_block, false);
533 fill_block(zero_block, address_block, address_block, false);
534 end;
535
536 function index_alpha(const instance: Pargon2_instance_t;
537 const position: Pargon2_position_t; pseudo_rand: cuint32;
538 same_lane: boolean): cuint32;
539 var
540 reference_area_size: cuint32;
541 relative_position: cuint64;
542 start_position, absolute_position: cuint32;
543 begin
544 (*
545 * Pass 0:
546 * This lane : all already finished segments plus already constructed
547 * blocks in this segment
548 * Other lanes : all already finished segments
549 * Pass 1+:
550 * This lane : (SYNC_POINTS - 1) last segments plus already constructed
551 * blocks in this segment
552 * Other lanes : (SYNC_POINTS - 1) last segments
553 *)
554
555 if (0 = position^.pass) then
556 begin
557 //* First pass */
558 if (0 = position^.slice) then
559 begin
560 //* First slice */
561 reference_area_size :=
562 position^.index - 1; //* all but the previous */
563 end
564 else begin
565 if (same_lane) then
566 begin
567 //* The same lane => add current segment */
568 reference_area_size :=
569 position^.slice * instance^.segment_length +
570 position^.index - 1;
571 end
572 else begin
573 reference_area_size :=
574 position^.slice * instance^.segment_length +
575 IfThen((position^.index = 0), (-1), 0);
576 end;
577 end
578 end
579 else begin
580 //* Second pass */
581 if (same_lane) then
582 begin
583 reference_area_size := instance^.lane_length -
584 instance^.segment_length + position^.index - 1;
585 end
586 else begin
587 reference_area_size := instance^.lane_length -
588 instance^.segment_length +
589 IfThen((position^.index = 0), (-1), 0);
590 end;
591 end;
592
593 (* 1.2.4. Mapping pseudo_rand to 0..<reference_area_size-1> and produce
594 * relative position *)
595 relative_position := pseudo_rand;
596 relative_position := relative_position * relative_position shr 32;
597 relative_position := reference_area_size - 1 -
598 (reference_area_size * relative_position shr 32);
599
600 //* 1.2.5 Computing starting position */
601 start_position := 0;
602
603 if (0 <> position^.pass) then
604 begin
605 start_position := IfThen(position^.slice = ARGON2_SYNC_POINTS - 1,
606 0,
607 (position^.slice + 1) * instance^.segment_length);
608 end;
609
610 //* 1.2.6. Computing absolute position */
611 absolute_position := (start_position + relative_position) mod
612 instance^.lane_length; //* absolute position */
613 Result:= absolute_position;
614 end;
615
616 procedure fill_segment(position_lane: PtrInt; Data: Pointer; {%H-}Item: TObject);
617 var
618 ref_block: Pblock = nil;
619 curr_block: Pblock = nil;
620 address_block, input_block, zero_block: Tblock;
621 pseudo_rand, ref_index, ref_lane: cuint64;
622 prev_offset, curr_offset: cuint32;
623 starting_index: cuint32;
624 i: cuint32;
625 data_independent_addressing: boolean;
626 position: Targon2_position_t;
627 instance: Pargon2_instance_t absolute position.instance_ptr;
628 begin
629 if (Data = nil) then Exit;
630
631 position := Pargon2_position_t(Data)^;
632
633 data_independent_addressing :=
634 (instance^.type_ = Argon2_i) or
635 ((instance^.type_ = Argon2_id) and (position.pass = 0) and
636 (position.slice < ARGON2_SYNC_POINTS div 2));
637
638 if (data_independent_addressing) then
639 begin
640 init_block_value(@zero_block, 0);
641 init_block_value(@input_block, 0);
642
643 input_block.v[0] := position.pass;
644 input_block.v[1] := position_lane;
645 input_block.v[2] := position.slice;
646 input_block.v[3] := instance^.memory_blocks;
647 input_block.v[4] := instance^.passes;
648 input_block.v[5] := cuint64(instance^.type_);
649 end;
650
651 position.index := 0;
652 starting_index := 0;
653
654 if ((0 = position.pass) and (0 = position.slice)) then
655 begin
656 starting_index := 2; //* we have already generated the first two blocks */
657
658 //* Don't forget to generate the first block of addresses: */
659 if (data_independent_addressing) then begin
660 next_addresses(@address_block, @input_block, @zero_block);
661 end;
662 end;
663
664 //* Offset of the current block */
665 curr_offset := position_lane * instance^.lane_length +
666 position.slice * instance^.segment_length + starting_index;
667
668 if (0 = curr_offset mod instance^.lane_length) then
669 begin
670 //* Last block in this lane */
671 prev_offset := curr_offset + instance^.lane_length - 1;
672 end
673 else begin
674 //* Previous block */
675 prev_offset := curr_offset - 1;
676 end;
677
678 for i := starting_index to instance^.segment_length - 1 do
679 begin
680 //*1.1 Rotating prev_offset if needed */
681 if (curr_offset mod instance^.lane_length = 1) then begin
682 prev_offset := curr_offset - 1;
683 end;
684
685 //* 1.2 Computing the index of the reference block */
686 //* 1.2.1 Taking pseudo-random value from the previous block */
687 if (data_independent_addressing) then
688
689 begin
690 if (i mod ARGON2_ADDRESSES_IN_BLOCK = 0) then begin
691 next_addresses(@address_block, @input_block, @zero_block);
692 end;
693 pseudo_rand := address_block.v[i mod ARGON2_ADDRESSES_IN_BLOCK];
694 end
695 else begin
696 pseudo_rand := instance^.memory[prev_offset].v[0];
697 end;
698
699 //* 1.2.2 Computing the lane of the reference block */
700 ref_lane := ((pseudo_rand shr 32)) mod instance^.lanes;
701
702 if ((position.pass = 0) and (position.slice = 0)) then begin
703 //* Can not reference other lanes yet */
704 ref_lane := position_lane;
705 end;
706
707 //* 1.2.3 Computing the number of possible reference block within the lane. */
708 position.index := i;
709 ref_index := index_alpha(instance, @position, pseudo_rand and $FFFFFFFF,
710 ref_lane = position_lane);
711
712 //* 2 Creating a new block */
713 ref_block :=
714 instance^.memory + instance^.lane_length * ref_lane + ref_index;
715 curr_block := instance^.memory + curr_offset;
716 if (ARGON2_VERSION_10 = instance^.version) then begin
717 //* version 1.2.1 and earlier: overwrite, not XOR */
718 fill_block(instance^.memory + prev_offset, ref_block, curr_block, false);
719 end
720 else begin
721 if (0 = position.pass) then begin
722 fill_block(instance^.memory + prev_offset, ref_block,
723 curr_block, false);
724 end
725 else begin
726 fill_block(instance^.memory + prev_offset, ref_block,
727 curr_block, true);
728 end;
729 end;
730
731 Inc(curr_offset);
732 Inc(prev_offset);
733 end;
734 end;
735
736 procedure finalize(const context: Pargon2_context; instance: Pargon2_instance_t);
737 var
738 l: cuint32;
739 blockhash: Tblock;
740 last_block_in_lane: cuint32;
741 blockhash_bytes: array [0..ARGON2_BLOCK_SIZE-1] of cuint8;
742 begin
743 if (context <> nil) and (instance <> nil) then
744 begin
745 copy_block(@blockhash, instance^.memory + instance^.lane_length - 1);
746
747 //* XOR the last blocks */
748 for l := 1 to instance^.lanes - 1 do
749 begin
750 last_block_in_lane := l * instance^.lane_length + (instance^.lane_length - 1);
751 xor_block(@blockhash, instance^.memory + last_block_in_lane);
752 end;
753
754 //* Hash the result */
755 begin
756 store_block(@blockhash_bytes[0], @blockhash);
757 blake2b_long(context^.out_, context^.outlen, @blockhash_bytes[0],
758 ARGON2_BLOCK_SIZE);
759 //* clear blockhash and blockhash_bytes */
760 clear_internal_memory(@blockhash.v[0], ARGON2_BLOCK_SIZE);
761 clear_internal_memory(@blockhash_bytes[0], ARGON2_BLOCK_SIZE);
762 end;
763
764 {$IFDEF GENKAT}
765 print_tag(context^.out_, context^.outlen);
766 {$ENDIF}
767
768 free_memory(pcuint8(instance^.memory),
769 instance^.memory_blocks, sizeof(Tblock));
770 end;
771 end;
772
773 function fill_memory_blocks(instance: Pargon2_instance_t): cint;
774 var
775 r, s, l: cuint32;
776 position: Targon2_position_t;
777 begin
778 if (instance = nil) or (instance^.lanes = 0) then begin
779 Exit(ARGON2_INCORRECT_PARAMETER);
780 end;
781 position.instance_ptr:= instance;
782 for r := 0 to instance^.passes - 1 do
783 begin
784 position.pass:= r;
785 for s := 0 to ARGON2_SYNC_POINTS - 1 do
786 begin
787 position.slice:= s;
788 {$IF DEFINED(USE_MTPROCS)}
789 if instance^.lanes > 1 then
790 ProcThreadPool.DoParallel(TMTProcedure(@fill_segment), 0, instance^.lanes - 1, @position)
791 else
792 {$ENDIF}
793 for l := 0 to instance^.lanes - 1 do fill_segment(l, @position, nil);
794 end;
795 {$IFDEF GENKAT}
796 internal_kat(instance, r); ///* Print all memory blocks */
797 {$ENDIF}
798 end;
799 Result:= ARGON2_OK;
800 end;
801
802 procedure fill_first_blocks(blockhash: pcuint8; const instance: pargon2_instance_t);
803 var
804 l: cuint32;
805 blockhash_bytes: array[0..ARGON2_BLOCK_SIZE-1] of cuint8;
806 begin
807 //* Make the first and second block in each lane as G(H0||0||i) or G(H0||1||i) */
808 for l := 0 to instance^.lanes - 1 do
809 begin
810 store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0);
811 store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l);
812 blake2b_long(@blockhash_bytes[0], ARGON2_BLOCK_SIZE, blockhash,
813 ARGON2_PREHASH_SEED_LENGTH);
814 load_block(@instance^.memory[l * instance^.lane_length + 0],
815 blockhash_bytes);
816
817 store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1);
818 blake2b_long(@blockhash_bytes[0], ARGON2_BLOCK_SIZE, blockhash,
819 ARGON2_PREHASH_SEED_LENGTH);
820 load_block(@instance^.memory[l * instance^.lane_length + 1],
821 blockhash_bytes);
822 end;
823 clear_internal_memory(@blockhash_bytes[0], ARGON2_BLOCK_SIZE);
824 end;
825
826 procedure initial_hash(blockhash: pcuint8; context: Pargon2_context;
827 type_: Targon2_type);
828 var
829 BlakeHash: blake2b_state;
830 value: array[0..sizeof(cuint32)-1] of cuint8;
831 begin
832 if (nil = context) or (nil = blockhash) then Exit;
833
834 blake2b_init(@BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH);
835
836 store32(@value[0], context^.lanes);
837 blake2b_update(@BlakeHash, @value[0], sizeof(value));
838
839 store32(@value[0], context^.outlen);
840 blake2b_update(@BlakeHash, @value[0], sizeof(value));
841
842 store32(@value[0], context^.m_cost);
843 blake2b_update(@BlakeHash, @value[0], sizeof(value));
844
845 store32(@value[0], context^.t_cost);
846 blake2b_update(@BlakeHash, @value[0], sizeof(value));
847
848 store32(@value[0], context^.version);
849 blake2b_update(@BlakeHash, @value[0], sizeof(value));
850
851 store32(@value[0], cuint32(type_));
852 blake2b_update(@BlakeHash, @value[0], sizeof(value));
853
854 store32(@value[0], context^.pwdlen);
855 blake2b_update(@BlakeHash, @value[0], sizeof(value));
856
857 if (context^.pwd <> nil) then
858 begin
859 blake2b_update(@BlakeHash, context^.pwd,
860 context^.pwdlen);
861
862 if (context^.flags and ARGON2_FLAG_CLEAR_PASSWORD <> 0) then
863 begin
864 secure_wipe_memory(context^.pwd, context^.pwdlen);
865 context^.pwdlen := 0;
866 end;
867 end;
868
869 store32(@value[0], context^.saltlen);
870 blake2b_update(@BlakeHash, @value[0], sizeof(value));
871
872 if (context^.salt <> nil) then
873 begin
874 blake2b_update(@BlakeHash, context^.salt,
875 context^.saltlen);
876 end;
877
878 store32(@value[0], context^.secretlen);
879 blake2b_update(@BlakeHash, @value[0], sizeof(value));
880
881 if (context^.secret <> nil) then
882 begin
883 blake2b_update(@BlakeHash, context^.secret,
884 context^.secretlen);
885
886 if (context^.flags and ARGON2_FLAG_CLEAR_SECRET <> 0) then
887 begin
888 secure_wipe_memory(context^.secret, context^.secretlen);
889 context^.secretlen := 0;
890 end;
891 end;
892
893 store32(@value[0], context^.adlen);
894 blake2b_update(@BlakeHash, @value[0], sizeof(value));
895
896 if (context^.ad <> nil) then
897 begin
898 blake2b_update(@BlakeHash, context^.ad,
899 context^.adlen);
900 end;
901
902 blake2b_final(@BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH);
903 end;
904
905 function initialize(instance: Pargon2_instance_t; context: Pargon2_context): cint;
906 var
907 blockhash: array[0..ARGON2_PREHASH_SEED_LENGTH-1] of cuint8;
908 begin
909 instance^.context_ptr := context;
910
911 //* 1. Memory allocation */
912 result := allocate_memory(@(instance^.memory),
913 instance^.memory_blocks, sizeof(Tblock));
914 if (result <> ARGON2_OK) then Exit;
915
916 (* 2. Initial hashing */
917 /* H_0 + 8 extra bytes to produce the first blocks */
918 /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */
919 /* Hashing all inputs *)
920 initial_hash(blockhash, context, instance^.type_);
921 //* Zeroing 8 extra bytes */
922 clear_internal_memory(@blockhash[ARGON2_PREHASH_DIGEST_LENGTH],
923 ARGON2_PREHASH_SEED_LENGTH -
924 ARGON2_PREHASH_DIGEST_LENGTH);
925
926 {$IFDEF GENKAT}
927 initial_kat(blockhash, context, instance^.type_);
928 {$ENDIF}
929
930 //* 3. Creating first blocks, we always have at least two blocks in a slice */
931 fill_first_blocks(blockhash, instance);
932 //* Clearing the hash */
933 clear_internal_memory(@blockhash[0], ARGON2_PREHASH_SEED_LENGTH);
934
935 Result:= ARGON2_OK;
936 end;
937
938 function argon2_ctx(context: Pargon2_context; type_: Targon2_type): cint;
939 var
940 memory_blocks, segment_length: cuint32;
941 instance: Targon2_instance_t;
942 begin
943 (*
944 //* 1. Validate all inputs */
945 int result = validate_inputs(context);
946
947 if (ARGON2_OK != result) {
948 return result;
949 }
950
951 if (Argon2_d != type && Argon2_i != type && Argon2_id != type) {
952 return ARGON2_INCORRECT_TYPE;
953 }
954 *)
955
956 //* 2. Align memory size */
957 //* Minimum memory_blocks = 8L blocks, where L is the number of lanes */
958 memory_blocks := context^.m_cost;
959
960 if (memory_blocks < 2 * ARGON2_SYNC_POINTS * context^.lanes) then begin
961 memory_blocks := 2 * ARGON2_SYNC_POINTS * context^.lanes;
962 end;
963
964 segment_length := memory_blocks div (context^.lanes * ARGON2_SYNC_POINTS);
965 //* Ensure that all segments have equal length */
966 memory_blocks := segment_length * (context^.lanes * ARGON2_SYNC_POINTS);
967
968 instance.version := Targon2_version(context^.version);
969 instance.memory := nil;
970 instance.passes := context^.t_cost;
971 instance.memory_blocks := memory_blocks;
972 instance.segment_length := segment_length;
973 instance.lane_length := segment_length * ARGON2_SYNC_POINTS;
974 instance.lanes := context^.lanes;
975 instance.threads := context^.threads;
976 instance.type_ := type_;
977
978 if (instance.threads > instance.lanes) then begin
979 instance.threads := instance.lanes;
980 end;
981
982 //* 3. Initialization: Hashing inputs, allocating memory, filling first blocks */
983 result := initialize(@instance, context);
984
985 if (ARGON2_OK <> result) then Exit;
986
987 //* 4. Filling memory */
988 result := fill_memory_blocks(@instance);
989
990 if (ARGON2_OK <> result) then Exit;
991
992 //* 5. Finalization */
993 finalize(context, @instance);
994
995 Result:= ARGON2_OK;
996 end;
997
998 function argon2_hash(const t_cost, m_cost, parallelism: cuint32;
999 const pwd: pansichar; const pwdlen: csize_t;
1000 const salt: pansichar; const saltlen: csize_t;
1001 const secret: pansichar; const secretlen: csize_t;
1002 const ad: pansichar; const adlen: csize_t;
1003 hash: Pointer; const hashlen: csize_t;
1004 type_: Targon2_type; version: Targon2_version): cint;
1005 var
1006 context: Targon2_context;
1007 begin
1008 (*
1009 if (pwdlen > ARGON2_MAX_PWD_LENGTH) {
1010 return ARGON2_PWD_TOO_LONG;
1011 }
1012
1013 if (saltlen > ARGON2_MAX_SALT_LENGTH) {
1014 return ARGON2_SALT_TOO_LONG;
1015 }
1016
1017 if (hashlen > ARGON2_MAX_OUTLEN) {
1018 return ARGON2_OUTPUT_TOO_LONG;
1019 }
1020
1021 if (hashlen < ARGON2_MIN_OUTLEN) {
1022 return ARGON2_OUTPUT_TOO_SHORT;
1023 }
1024 *)
1025 context.out_ := GetMem(hashlen);
1026
1027 if (context.out_ = nil) then begin
1028 Exit(ARGON2_MEMORY_ALLOCATION_ERROR);
1029 end;
1030
1031 context.outlen := cuint32(hashlen);
1032 context.pwd := pcuint8(pwd);
1033 context.pwdlen := cuint32(pwdlen);
1034 context.salt := pcuint8(salt);
1035 context.saltlen := cuint32(saltlen);
1036 context.secret := pcuint8(secret);
1037 context.secretlen := secretlen;
1038 context.ad := pcuint8(ad);
1039 context.adlen := adlen;
1040 context.t_cost := t_cost;
1041 context.m_cost := m_cost;
1042 context.lanes := parallelism;
1043 context.threads := parallelism;
1044 context.flags := ARGON2_DEFAULT_FLAGS;
1045 context.version := cuint32(version);
1046
1047 result := argon2_ctx(@context, type_);
1048
1049 //* if raw hash requested, write it */
1050 if (result = ARGON2_OK) and (hash <> nil) then
1051 begin
1052 Move(context.out_^, hash^, hashlen);
1053 end;
1054
1055 clear_internal_memory(context.out_, hashlen);
1056 FreeMem(context.out_);
1057 end;
1058
1059 function argon2id_kdf(const t_cost, m_cost, parallelism: cuint32;
1060 const pwd: pansichar; const pwdlen: csize_t;
1061 const salt: pansichar; const saltlen: csize_t;
1062 hash: Pointer; const hashlen: csize_t): cint;
1063 begin
1064 Result:= argon2_hash(t_cost, m_cost, parallelism, pwd, pwdlen, salt, saltlen, nil, 0,
1065 nil, 0, hash, hashlen, Argon2_id, ARGON2_VERSION_NUMBER);
1066 end;
1067
1068 function argon2_selftest: Boolean;
1069
1070 function hash_test(version: Targon2_version; type_: Targon2_type; t, m, p: cuint32; pwd, salt, hex: String): Boolean;
1071 var
1072 Q: QWord;
1073 out_: String;
1074 out_hex: String;
1075 out_len: Integer;
1076 begin
1077 out_len:= Length(hex) div 2;
1078 WriteLn(Format('Hash test: $v=%d t=%d, m=%d, p=%d, pass=%s, salt=%s, result=%d',
1079 [version, t, m, p, pwd, salt, out_len]));
1080
1081 SetLength(out_, out_len);
1082 Q:= GetTickCount64;
1083 argon2_hash(t, 1 shl m, p, Pointer(pwd), Length(pwd), Pointer(salt), Length(salt),
1084 nil, 0, nil, 0, Pointer(out_), OUT_LEN, type_, version);
1085 WriteLn('Time: ', GetTickCount64 - Q);
1086 SetLength(out_hex, OUT_LEN * 2);
1087 BinToHex(PAnsiChar(out_), PAnsiChar(out_hex), OUT_LEN);
1088 Result:= SameText(hex, out_hex);
1089 WriteLn('Must: ', hex);
1090 WriteLn('Have: ', out_hex);
1091 WriteLn('Result: ', Result);
1092 WriteLn('------------------------------------------------------------');
1093 end;
1094
1095 begin
1096 Result:= True;
1097 // Test Argon2i
1098 Result:= Result and hash_test(ARGON2_VERSION_10, Argon2_i, 2, 16, 1, 'password', 'somesalt',
1099 'f6c4db4a54e2a370627aff3db6176b94a2a209a62c8e36152711802f7b30c694');
1100 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_i, 2, 16, 1, 'password', 'somesalt',
1101 'c1628832147d9720c5bd1cfd61367078729f6dfb6f8fea9ff98158e0d7816ed0');
1102 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_i, 2, 16, 1, 'differentpassword', 'somesalt',
1103 '14ae8da01afea8700c2358dcef7c5358d9021282bd88663a4562f59fb74d22ee');
1104 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_i, 2, 16, 1, 'password', 'diffsalt',
1105 'b0357cccfbef91f3860b0dba447b2348cbefecadaf990abfe9cc40726c521271');
1106 // Test Argon2d
1107 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_d, 2, 16, 1, 'password', 'somesalt',
1108 '955e5d5b163a1b60bba35fc36d0496474fba4f6b59ad53628666f07fb2f93eaf');
1109 // Test Argon2id
1110 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_id, 2, 16, 1, 'password', 'somesalt',
1111 '09316115d5cf24ed5a15a31a3ba326e5cf32edc24702987c02b6566f61913cf7');
1112 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_id, 2, 16, 2, 'password', 'somesalt',
1113 '6f681ac1c3384a90119d2763a683f9ac79532d999abfab5644aa8aafd3d0d234');
1114 // Recommended parameters (the running time about 125ms on Intel Core i5-7400 64 bit)
1115 Result:= Result and hash_test(ARGON2_VERSION_NUMBER, Argon2_id, 2, 16, 4,
1116 'password','123456789012345678901234567890xy',
1117 'c80142cbb6076b2d6be20137ddf24679cfc70eb4cde0f242a342e9e63636292eb2efcd907873fc19ca0bee0b7d7e992a7f68ce24a2da379bc41d5eb235f76eaa17220a6fa82d2d4a2e168b021dbfa5ba5a9f232ea0a1e24d');
1118 WriteLn('Result: ', Result);
1119 end;
1120
1121 end.