Debian Codegraph @

components/kascrypt/Hashes/Private/sha3.pas

raw
1 unit SHA3;
2
3 {SHA3 functions (including SHAKE) based on Keccak}
4
5 interface
6
7 {$i STD.INC}
8
9 {$ifdef FPC}
10 {$ifdef CPUI386}
11 {$define USE_MMXCODE}
12 {$endif}
13 {$ifdef CPU64}
14 {$define USE_64BITCODE}
15 {$endif}
16 {$endif}
17
18 {.$define USE_64BITCODE} {Use 64-bit for Keccak permutation}
19 {.$define USE_MMXCODE } {Use MMX for Keccak permutation, contributed by Eric Grange}
20 {.$define USE_MMX_AKP } {Use MMX for Keccak permutation, contributed by Anna Kaliszewicz / payl}
21
22 (*************************************************************************
23
24 DESCRIPTION : SHA3 functions (including SHAKE) based on Keccak
25
26 REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP
27
28 EXTERNAL DATA : ---
29
30 MEMORY USAGE : ---
31
32 DISPLAY MODE : ---
33
34 REFERENCES : SHA3:
35 FIPS 202 SHA-3 Standard: 'Permutation-Based Hash and
36 Extendable-Output Functions' available from
37 http://csrc.nist.gov/publications/PubsFIPS.html or
38 http://dx.doi.org/10.6028/NIST.FIPS.202 or
39 http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
40 Keccak:
41 https://github.com/gvanas/KeccakCodePackage
42 http://keccak.noekeon.org/KeccakReferenceAndOptimized-3.2.zip
43 http://keccak.noekeon.org/KeccakKAT-3.zip (17MB)
44 http://csrc.nist.gov/groups/ST/hash/documents/SHA3-C-API.pdf
45
46 REMARKS : 1. For 32-bit compilers with int64 (FPC, D6+) there are
47 conditional defines to optionally use MMX or 64-bit code.
48 2. The current implementation needs little-endian machines
49
50 Version Date Author Modification
51 ------- -------- ------- ------------------------------------------
52 0.01 17.10.12 W.Ehrhardt Initial BP7 version from Keccak-simple32BI.c
53 0.02 18.10.12 we Fixed buf in xorIntoState
54 0.03 18.10.12 we Other compilers
55 0.04 19.10.12 we Separate unit
56 0.05 20.10.12 we Functions from KeccakSponge
57 0.06 21.10.12 we Functions from KeccakNISTInterface
58 0.07 21.10.12 we D2-D6 with ASM RotL function
59 0.08 22.10.12 we Include files keccperm.i16 and .i32
60 0.09 22.10.12 we __P2I type casts removed
61 0.10 22.10.12 we References, comments, remarks
62 0.11 25.10.12 we Make partialBlock longint
63 0.12 30.10.12 we Packed arrays, type TKDQueue
64 0.13 31.10.12 we Partially unrolled 64-bit code from Keccak-inplace.c
65 0.14 01.11.12 we Compact 64-bit code from Botan
66 0.15 02.11.12 we 64-bit code about 20% faster with local data
67 0.16 09.11.12 we KeccakFullBytes, TKeccakMaxDigest
68 0.17 12.11.12 we USE32BIT forces skipping of 64-bit code
69
70 0.18 12.04.14 we Unit renamed to SHA3, SHA3 type definitions
71 0.19 12.04.14 we SHA3_Init, SHA3_Update, SHA3_FinalEx
72 0.20 13.04.14 we SHA3_UpdateXL, SHA3_FinalHash, byte sized messages work
73 0.21 14.04.14 we LSB bit sized messages, SHA3_FinalBit_LSB, working SHAKE
74 0.22 11.05.14 we Fix duplicate return result and a few typos
75
76 0.23 08.08.15 we TSpongeState with words and Fill3, assert HASHCTXSIZE
77 0.24 09.08.15 we SHA3_FinalBit update final bits in MSB format
78 0.25 09.08.15 we Removed unused Keccak leftovers
79 0.26 09.08.15 we Error field in context, rewrite error handling
80 0.27 16.08.15 we Some code cleanup
81 0.28 17.08.15 we Updated references
82 0.29 26.08.15 we $defines USE_64BITCODE, USE_MMXCODE
83 0.30 23.04.16 we USE_MMX_AKP
84
85 *************************************************************************)
86
87
88 (*-------------------------------------------------------------------------
89 (C) Copyright 2012-2016 Wolfgang Ehrhardt
90
91 This software is provided 'as-is', without any express or implied warranty.
92 In no event will the authors be held liable for any damages arising from
93 the use of this software.
94
95 Permission is granted to anyone to use this software for any purpose,
96 including commercial applications, and to alter it and redistribute it
97 freely, subject to the following restrictions:
98
99 1. The origin of this software must not be misrepresented; you must not
100 claim that you wrote the original software. If you use this software in
101 a product, an acknowledgment in the product documentation would be
102 appreciated but is not required.
103
104 2. Altered source versions must be plainly marked as such, and must not be
105 misrepresented as being the original software.
106
107 3. This notice may not be removed or altered from any source distribution.
108
109
110 ---------------------------------------------------------------------------
111 *NOTE FROM THE DESIGNERS OF KECCAK*
112
113 The Keccak sponge function, designed by Guido Bertoni, Joan Daemen,
114 Michael Peeters and Gilles Van Assche. For more information, feedback or
115 questions, please refer to our website: http://keccak.noekeon.org/
116
117 Implementation by the designers (and Ronny Van Keer), hereby denoted
118 as "the implementer".
119
120 To the extent possible under law, the implementer has waived all copyright
121 and related or neighboring rights to the source code in this file.
122 http://creativecommons.org/publicdomain/zero/1.0/
123
124 ----------------------------------------------------------------------------*)
125
126 uses
127 BTypes, Hash;
128
129 const
130 SHA3_ERR_INVALID_ALG = 1;
131 SHA3_ERR_WRONG_FINAL = 2;
132
133 const
134 KeccakPermutationSize = 1600;
135 KeccakMaximumRate = 1536;
136 KeccakPermutationSizeInBytes = KeccakPermutationSize div 8;
137 KeccakMaximumRateInBytes = KeccakMaximumRate div 8;
138
139 type
140 TState_B = packed array[0..KeccakPermutationSizeInBytes-1] of byte;
141 TState_L = packed array[0..(KeccakPermutationSizeInBytes) div 4 - 1] of longint;
142 TKDQueue = packed array[0..KeccakMaximumRateInBytes-1] of byte;
143
144 type
145 TSpongeState = packed record
146 state: TState_B;
147 dataQueue: TKDQueue;
148 rate: word;
149 capacity: word;
150 bitsInQueue: word;
151 fixedOutputLength: word;
152 bitsAvailableForSqueezing: word;
153 squeezing: word;
154 Error: int16;
155 Fill3: packed array[407..HASHCTXSIZE] of byte;
156 end;
157
158
159 {---------------------------------------------------------------------------}
160 {------------------ S H A 3 / S H A K E functions -----------------------}
161 {---------------------------------------------------------------------------}
162
163 type
164 TSHA3State = TSpongeState; {Hash state context}
165
166 type
167 TSHA3_Algo = (__SHA3_224, __SHA3_256, __SHA3_384, __SHA3_512, __SHAKE_128, __SHAKE_256);
168
169 function SHA3_Init(var state: TSHA3State; algo: TSHA3_Algo): integer;
170 {-Initialize the state of the Keccak[r, c] sponge function. The rate r and the}
171 { capacity c values are determined from the SHA3 algorithm. Result 0=success. }
172
173 function SHA3_UpdateXL(var state: TSHA3State; Msg: pointer; Len: longint): integer;
174 {-Update context with Msg data of Len bytes}
175
176 function SHA3_Update(var state: TSHA3State; Msg: pointer; Len: word): integer;
177 {-Update context with Msg data of Len bytes}
178
179 function SHA3_FinalHash(var state: TSHA3State; digest: pointer): integer;
180 {-Compute SHA3 hash digest and store into hashval. Only for hash}
181 { algorithms, result WRONG_FINAL if called for SHAKE functions. }
182
183 function SHA3_FinalBit_LSB(var state: TSHA3State; bits: byte; bitlen: integer; hashval: pointer; numbits: longint): integer;
184 {-Update final bits in LSB format, pad, and compute hashval}
185
186 function SHA3_FinalBit(var state: TSHA3State; bits: byte; bitlen: integer; hashval: pointer; numbits: longint): integer;
187 {-Update final bits in MSB format, pad, and compute hashval}
188
189
190 {SHA3_LastError is set by SHA-3 functions which return an error code, where other}
191 {units/algorithms use procedures. Note that the error variable should be treated }
192 {as dummy because it is shared over all contexts/threads etc. The context field }
193 {TSHA3State.error is used to handle context related errors. It will be set to }
194 {0=no error during context initialization.}
195
196 var
197 SHA3_LastError: integer;
198
199
200 implementation
201
202
203 const
204 cKeccakNumberOfRounds = 24;
205
206 {---------------------------------------------------------------------------}
207 {Helper types}
208
209 {$ifndef BIT16}
210 type
211 TBABytes = array[0..MaxLongint-1] of byte;
212 {$else}
213 type
214 TBABytes = array[0..$FFF0-1] of byte;
215 {$endif}
216
217 type
218 PBA = ^TBABytes;
219
220
221 {---------------------------------------------------------------------------}
222 {$ifndef BIT16}
223 {$ifdef BIT64}
224 {$define USE_64BITCODE}
225 {$else}
226 {$ifndef FPC}
227 {$ifndef CONDITIONALEXPRESSIONS}
228 {Delphi 5 or lower}
229 {$undef USE_MMXCODE}
230 {$undef USE_MMX_AKP}
231 {$endif}
232 {$endif}
233 {$endif}
234 {$ifdef USE_64BITCODE}
235 {$i kperm_64.inc}
236 {$ifdef HAS_MSG}
237 {.$message '* using 64-bit code'}
238 {$endif}
239 {$else}
240 {$ifdef USE_MMXCODE}
241 {$i kperm_mx.inc}
242 {$ifdef HAS_MSG}
243 {$message '* using mmx code (32Bit/eg)'}
244 {$endif}
245 {$else}
246 {$ifdef USE_MMX_AKP}
247 {$i kperm_mp.inc}
248 {$ifdef HAS_MSG}
249 {$message '* using mmx code (32Bit/akp)'}
250 {$endif}
251 {$else}
252 {$i kperm_32.inc}
253 {$endif}
254 {$endif}
255 {$endif}
256 {$else}
257 {$i kperm_16.inc}
258 {$endif}
259
260
261 {---------------------------------------------------------------------------}
262 procedure KeccakAbsorb(var state: TState_B; data: pointer; laneCount: integer);
263 begin
264 xorIntoState(TState_L(state),data,laneCount);
265 KeccakPermutation(TState_L(state));
266 end;
267
268
269 {---------------------------------------------------------------------------}
270 function InitSponge(var state: TSpongeState; rate, capacity: integer): integer;
271 {-Function to initialize the state of the Keccak sponge function.}
272 { The sponge function is set to the absorbing phase. Result=0 if }
273 { success, 1 if rate and/or capacity are invalid.}
274 begin
275 InitSponge := 1;
276 {This is the only place where state.error is reset to 0 = SUCCESS}
277 fillchar(state, sizeof(state),0);
278 if (rate+capacity <> 1600) or (rate <= 0) or (rate >= 1600) or ((rate and 63) <> 0) then begin
279 state.error := 1;
280 exit;
281 end;
282 state.rate := rate;
283 state.capacity := capacity;
284 InitSponge := 0;
285 end;
286
287
288 {---------------------------------------------------------------------------}
289 procedure AbsorbQueue(var state: TSpongeState);
290 {-Absorb remaining bits from queue}
291 begin
292 {state.bitsInQueue is assumed to be equal to state.rate}
293 KeccakAbsorb(state.state, @state.dataQueue, state.rate div 64);
294 state.bitsInQueue := 0;
295 end;
296
297
298 {---------------------------------------------------------------------------}
299 function Absorb(var state: TSpongeState; data: pointer; databitlen: longint): integer;
300 {-Function to give input data for the sponge function to absorb}
301 var
302 i, j, wholeBlocks, partialBlock: longint;
303 partialByte: integer;
304 curData: pByte;
305 begin
306 Absorb := 1;
307 if state.error<>0 then exit; {No further action}
308 if (state.bitsInQueue and 7 <> 0) or (state.squeezing<>0) then begin
309 {Only the last call may contain a partial byte}
310 {and additional input if squeezing}
311 state.error := 1;
312 exit;
313 end;
314 i := 0;
315 while i < databitlen do begin
316 if ((state.bitsInQueue=0) and (databitlen >= state.rate) and (i <= (databitlen-state.rate))) then begin
317 wholeBlocks := (databitlen-i) div state.rate;
318 curData := @PBA(data)^[i div 8];
319 j := 0;
320 while j<wholeBlocks do begin
321 KeccakAbsorb(state.state, curData, state.rate div 64);
322 inc(j);
323 inc(Ptr2Inc(curData), state.rate div 8);
324 end;
325 inc(i, wholeBlocks*state.rate);
326 end
327 else begin
328 partialBlock := databitlen - i;
329 if partialBlock+state.bitsInQueue > state.rate then begin
330 partialBlock := state.rate - state.bitsInQueue;
331 end;
332 partialByte := partialBlock and 7;
333 dec(partialBlock, partialByte);
334 move(PBA(data)^[i div 8], state.dataQueue[state.bitsInQueue div 8], partialBlock div 8);
335 inc(state.bitsInQueue, partialBlock);
336 inc(i, partialBlock);
337 if state.bitsInQueue=state.rate then AbsorbQueue(state);
338 if partialByte > 0 then begin
339 state.dataQueue[state.bitsInQueue div 8] := PBA(data)^[i div 8] and ((1 shl partialByte)-1);
340 inc(state.bitsInQueue, partialByte);
341 inc(i, partialByte);
342 end;
343 end;
344 end;
345 Absorb := 0;
346 end;
347
348
349 {---------------------------------------------------------------------------}
350 procedure PadAndSwitchToSqueezingPhase(var state: TSpongeState);
351 var
352 i: integer;
353 begin
354 {Note: the bits are numbered from 0=LSB to 7=MSB}
355 if (state.bitsInQueue + 1 = state.rate) then begin
356 i := state.bitsInQueue div 8;
357 state.dataQueue[i] := state.dataQueue[i] or (1 shl (state.bitsInQueue and 7));
358 AbsorbQueue(state);
359 fillchar(state.dataQueue, state.rate div 8, 0);
360 end
361 else begin
362 i := state.bitsInQueue div 8;
363 fillchar(state.dataQueue[(state.bitsInQueue+7) div 8], state.rate div 8 - (state.bitsInQueue+7) div 8,0);
364 state.dataQueue[i] := state.dataQueue[i] or (1 shl (state.bitsInQueue and 7));
365 end;
366 i := (state.rate-1) div 8;
367 state.dataQueue[i] := state.dataQueue[i] or (1 shl ((state.rate-1) and 7));
368 AbsorbQueue(state);
369 extractFromState(@state.dataQueue, TState_L(state.state), state.rate div 64);
370 state.bitsAvailableForSqueezing := state.rate;
371 state.squeezing := 1;
372 end;
373
374
375 {---------------------------------------------------------------------------}
376 function Squeeze(var state: TSpongeState; output: pointer; outputLength: longint): integer;
377 {-Squeeze output data from the sponge function. If the sponge function was }
378 { in the absorbing phase, this function switches it to the squeezing phase.}
379 { Returns 0 if successful, 1 otherwise. output: pointer to the buffer where}
380 { to store the output data; outputLength: number of output bits desired, }
381 { must be a multiple of 8.}
382 var
383 i: longint;
384 partialBlock: integer;
385 begin
386 Squeeze := 1;
387 if state.error<>0 then exit; {No further action}
388 if state.squeezing=0 then PadAndSwitchToSqueezingPhase(state);
389 if outputLength and 7 <> 0 then begin
390 {Only multiple of 8 bits are allowed, truncation can be done at user level}
391 state.error := 1;
392 exit;
393 end;
394 i := 0;
395 while i < outputLength do begin
396 if state.bitsAvailableForSqueezing=0 then begin
397 KeccakPermutation(TState_L(state.state));
398 extractFromState(@state.dataQueue, TState_L(state.state), state.rate div 64);
399 state.bitsAvailableForSqueezing := state.rate;
400 end;
401 partialBlock := state.bitsAvailableForSqueezing;
402 if partialBlock > outputLength - i then partialBlock := outputLength - i;
403 move(state.dataQueue[(state.rate - state.bitsAvailableForSqueezing) div 8], PBA(output)^[i div 8], partialBlock div 8);
404 dec(state.bitsAvailableForSqueezing, partialBlock);
405 inc(i,partialBlock);
406 end;
407 Squeeze := 0;
408 end;
409
410
411 {---------------------------------------------------------------------------}
412 function Update(var state: TSpongeState; data: pointer; databitlen: longint): integer;
413 {-Update state with databitlen bits from data. May be called multiple times, }
414 { only the last databitlen may be a non-multiple of 8 (the corresponding byte}
415 { must be MSB aligned, i.e. in the (databitlen and 7) most significant bits. }
416 var
417 ret: integer;
418 lastByte: byte;
419 begin
420 if state.error<>0 then begin
421 Update := state.error;
422 exit;
423 end;
424 if databitlen and 7 = 0 then ret := Absorb(state, data, databitlen)
425 else begin
426 ret := Absorb(state, data, databitlen - (databitlen and 7));
427 if ret=0 then begin
428 {Align the last partial byte to the least significant bits}
429 lastByte := PBA(data)^[databitlen div 8] shr (8 - (databitlen and 7));
430 ret := Absorb(state, @lastByte, databitlen and 7);
431 end
432 end;
433 update := ret;
434 {Update error only with old error=0, i.e. do no reset a non-zero value}
435 if state.error=0 then state.error := ret;
436 end;
437
438
439 {---------------------------------------------------------------------------}
440 {---------------------------------------------------------------------------}
441 {---------------------------------------------------------------------------}
442
443
444 {---------------------------------------------------------------------------}
445 function SHA3_Init(var state: TSHA3State; algo: TSHA3_Algo): integer;
446 {-Initialize the state of the Keccak[r, c] sponge function. The rate r and the}
447 { capacity c values are determined from the SHA3 algorithm. Result 0=success. }
448 const
449 FOL: array[TSHA3_Algo] of word = (224, 256, 384, 512, 0, 0);
450 begin
451 case algo of
452 __SHA3_224: SHA3_Init := InitSponge(state, 1152, 448);
453 __SHA3_256: SHA3_Init := InitSponge(state, 1088, 512);
454 __SHA3_384: SHA3_Init := InitSponge(state, 832, 768);
455 __SHA3_512: SHA3_Init := InitSponge(state, 576, 1024);
456 __SHAKE_128: SHA3_Init := InitSponge(state, 1344, 256);
457 __SHAKE_256: SHA3_Init := InitSponge(state, 1088, 512);
458 else begin
459 SHA3_Init := SHA3_ERR_INVALID_ALG;
460 state.error := SHA3_ERR_INVALID_ALG;
461 exit;
462 end;
463 end;
464 state.fixedOutputLength := FOL[algo];
465 end;
466
467
468 {---------------------------------------------------------------------------}
469 function SHA3_UpdateXL(var state: TSHA3State; Msg: pointer; Len: longint): integer;
470 {-Update context with Msg data of Len bytes}
471 begin
472 SHA3_UpdateXL := Absorb(state, Msg, Len*8);
473 end;
474
475
476 {---------------------------------------------------------------------------}
477 function SHA3_Update(var state: TSHA3State; Msg: pointer; Len: word): integer;
478 {-Update context with Msg data of Len bytes}
479 begin
480 SHA3_Update := SHA3_UpdateXL(state, Msg, Len);
481 end;
482
483
484 {---------------------------------------------------------------------------}
485 function SHA3_FinalHash(var state: TSHA3State; digest: pointer): integer;
486 {-Compute SHA3 hash digest and store into hashval. Only for hash}
487 { algorithms, result WRONG_FINAL if called for Shake functions. }
488 var
489 err: integer;
490 begin
491 err := 1;
492 if state.error=0 then begin
493 if state.fixedOutputLength=0 then err := SHA3_ERR_WRONG_FINAL
494 else err := SHA3_FinalBit_LSB(state, 0, 0, digest, state.fixedOutputLength);
495 end;
496 {Update error only with old error=0, i.e. do no reset a non-zero value}
497 if state.error=0 then state.error := err;
498 SHA3_FinalHash := err;
499 end;
500
501
502 {---------------------------------------------------------------------------}
503 function SHA3_FinalBit_LSB(var state: TSHA3State; bits: byte; bitlen: integer; hashval: pointer; numbits: longint): integer;
504 {-Update final bits in LSB format, pad, and compute hashval}
505 var
506 err,ll: integer;
507 lw: word;
508 begin
509 {normalize bitlen and bits (zero high bits)}
510 bitlen := bitlen and 7;
511 if bitlen=0 then lw := 0
512 else lw := bits and pred(word(1) shl bitlen);
513
514 {'append' (in LSB language) the domain separation bits}
515 if state.fixedOutputLength=0 then begin
516 {SHAKE: append four bits 1111}
517 lw := lw or (word($F) shl bitlen);
518 ll := bitlen+4;
519 end
520 else begin
521 {SHA3: append two bits 01}
522 lw := lw or (word($2) shl bitlen);
523 ll := bitlen+2;
524 end;
525
526 {update state with final bits}
527 if ll<9 then begin
528 {0..8 bits, one call to update}
529 lw := lw shl (8-ll);
530 err := update(state, @lw, ll);
531 {squeeze the digits from the sponge}
532 if err=0 then err := Squeeze(state, hashval, numbits);
533 end
534 else begin
535 {More than 8 bits, first a regular update with low byte}
536 err := update(state, @lw, 8);
537 if err=0 then begin
538 {Finally update remaining last bits}
539 dec(ll,8);
540 lw := lw shr ll;
541 err := update(state, @lw, ll);
542 if err=0 then err := Squeeze(state, hashval, numbits);
543 end;
544 end;
545 SHA3_FinalBit_LSB := err;
546 if state.error=0 then state.error := err;
547 end;
548
549
550 {---------------------------------------------------------------------------}
551 function SHA3_FinalBit(var state: TSHA3State; bits: byte; bitlen: integer; hashval: pointer; numbits: longint): integer;
552 {-Update final bits in MSB format, pad, and compute hashval}
553 var
554 i,m: integer;
555 r,b: byte;
556 begin
557 r := 0;
558 m := bitlen and $7;
559 if m>0 then begin
560 {right align the m bits}
561 b := bits shr (8-m);
562 {store reflected bits in r}
563 for i:=m downto 1 do begin
564 r := r + r + (b and 1);
565 b := b shr 1;
566 end;
567 end;
568 SHA3_FinalBit := SHA3_FinalBit_LSB(state,r,bitlen,hashval,numbits);
569 end;
570
571
572 begin
573 {$ifdef HAS_ASSERT}
574 assert(sizeof(TSHA3State)=HASHCTXSIZE , '** Invalid sizeof(TSHA3State)');
575 {$else}
576 if sizeof(THashContext)<>HASHCTXSIZE then RunError(227);
577 {$endif}
578 SHA3_LastError := 0;
579 end.