Debian Codegraph @

components/kascrypt/Hashes/Private/hash.pas

raw
1 unit Hash;
2
3 {General Hash Unit: This unit defines the common types, functions, and
4 procedures. Via Hash descriptors and corresponding pointers, algorithms
5 can be searched by name or by ID. More important: all supported algorithms
6 can be used in the HMAC and KDF constructions.}
7
8
9 interface
10
11 (*************************************************************************
12
13 DESCRIPTION : General hash unit: defines Algo IDs, digest types, etc
14
15 REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
16
17 EXTERNAL DATA : ---
18
19 MEMORY USAGE : ---
20
21 DISPLAY MODE : ---
22
23 REFERENCES : ---
24
25 REMARK : THashContext does not directly map the structure of the
26 context for SHA3 algorithms, a typecast with TSHA3State
27 from unit SHA3 should be used to access the fields.
28
29
30 Version Date Author Modification
31 ------- -------- ------- ------------------------------------------
32 0.10 15.01.06 W.Ehrhardt Initial version
33 0.11 15.01.06 we FindHash_by_ID, $ifdef DLL: stdcall
34 0.12 16.01.06 we FindHash_by_Name
35 0.13 18.01.06 we Descriptor fields HAlgNum, HSig
36 0.14 22.01.06 we Removed HSelfTest from descriptor
37 0.14 31.01.06 we RIPEMD-160, C_MinHash, C_MaxHash
38 0.15 11.02.06 we Fields: HDSize, HVersion, HPtrOID, HLenOID
39 0.16 02.08.06 we Packed arrays
40 0.17 07.08.06 we $ifdef BIT32: (const fname: shortstring...)
41 0.18 07.08.06 we C_HashVers = $00010002
42 0.19 10.02.07 we HashFile: no eof, XL and filemode via $ifdef
43 0.20 18.02.07 we MD4, C_HashVers = $00010003
44 0.21 22.02.07 we POID_Vec=^TOID_Vec, typed HPtrOID
45 0.22 24.02.07 we added some checks for HSig=C_HashSig
46 0.23 04.10.07 we THashContext.Index now longint
47 0.24 02.05.08 we type PHashDigest, function HashSameDigest
48 0.25 04.05.08 we BitAPI_Mask, BitAPI_PBit
49 0.26 05.05.08 we Descriptor with HFinalBit, C_HashVers=$00010004
50 0.27 20.05.08 we RMD160 as alias for RIPEMD160
51 0.28 12.11.08 we uses BTypes and Str255
52 0.29 19.07.09 we D12 fix: assign with typecast string(fname)
53 0.30 08.03.12 we SHA512/224 and SHA512/256, C_HashVers=$00010005
54 0.31 10.03.12 we HashFile: {$ifndef BIT16} instead of {$ifdef WIN32}
55
56 0.32 08.08.18 we New enlarged padded context, _SHA3_224 .. _SHA3_512
57 0.33 08.08.18 we THMacBuffer, assert HASHCTXSIZE
58 0.34 16.08.15 we Removed $ifdef DLL / stdcall
59
60 0.35 15.05.17 we Changes for Blake2s
61 0.36 16.05.17 we MaxOIDLen = 11 and MaxC_HashVers = $00020002
62
63 0.37 03.11.17 we TBlake2B_384/512Digest
64
65 **************************************************************************)
66
67 (*-------------------------------------------------------------------------
68 (C) Copyright 2006-2015 Wolfgang Ehrhardt
69
70 This software is provided 'as-is', without any express or implied warranty.
71 In no event will the authors be held liable for any damages arising from
72 the use of this software.
73
74 Permission is granted to anyone to use this software for any purpose,
75 including commercial applications, and to alter it and redistribute it
76 freely, subject to the following restrictions:
77
78 1. The origin of this software must not be misrepresented; you must not
79 claim that you wrote the original software. If you use this software in
80 a product, an acknowledgment in the product documentation would be
81 appreciated but is not required.
82
83 2. Altered source versions must be plainly marked as such, and must not be
84 misrepresented as being the original software.
85
86 3. This notice may not be removed or altered from any source distribution.
87 ----------------------------------------------------------------------------*)
88
89 {$i STD.INC}
90
91 uses
92 BTypes;
93
94 type
95 THashAlgorithm = (_MD4, _MD5, _RIPEMD160, _SHA1,
96 _SHA224, _SHA256, _SHA384, _SHA512,
97 _Whirlpool, _SHA512_224, _SHA512_256,
98 _SHA3_224, _SHA3_256, _SHA3_384, _SHA3_512,
99 _Blake2S_224, _Blake2S_256,
100 _Blake2B_384, _Blake2B_512); {Supported hash algorithms}
101
102 const
103 _RMD160 = _RIPEMD160; {Alias}
104
105 const
106 MaxBlockLen = 128; {Max. block length (buffer size), multiple of 4}
107 MaxDigestLen = 64; {Max. length of hash digest}
108 MaxStateLen = 16; {Max. size of internal state}
109 MaxOIDLen = 11; {Current max. OID length}
110 C_HashSig = $3D7A; {Signature for Hash descriptor}
111 C_HashVers = $00020002; {Version of Hash definitions}
112 C_MinHash = _MD4; {Lowest hash in THashAlgorithm}
113 C_MaxHash = _Blake2B_512;{Highest hash in THashAlgorithm}
114
115 type
116 THashState = packed array[0..MaxStateLen-1] of longint; {Internal state}
117 THashBuffer = packed array[0..MaxBlockLen-1] of byte; {hash buffer block}
118 THashDigest = packed array[0..MaxDigestLen-1] of byte; {hash digest}
119 PHashDigest = ^THashDigest; {pointer to hash digest}
120 THashBuf32 = packed array[0..MaxBlockLen div 4 -1] of longint; {type cast helper}
121 THashDig32 = packed array[0..MaxDigestLen div 4 -1] of longint; {type cast helper}
122 THMacBuffer = packed array[0..143] of byte; {hmac buffer block}
123
124 const
125 HASHCTXSIZE = 448; {Common size of enlarged padded old context}
126 {and new padded SHA3/SHAKE/Keccak context }
127
128 type
129 THashContext = packed record
130 Hash : THashState; {Working hash}
131 MLen : packed array[0..3] of longint; {max 128 bit msg length}
132 Buffer: THashBuffer; {Block buffer}
133 Index : longint; {Index in buffer}
134 Fill2 : packed array[213..HASHCTXSIZE] of byte;
135 end;
136
137 type
138 TMD4Digest = packed array[0..15] of byte; {MD4 digest }
139 TMD5Digest = packed array[0..15] of byte; {MD5 digest }
140 TRMD160Digest = packed array[0..19] of byte; {RMD160 digest }
141 TSHA1Digest = packed array[0..19] of byte; {SHA1 digest }
142 TSHA224Digest = packed array[0..27] of byte; {SHA224 digest }
143 TSHA256Digest = packed array[0..31] of byte; {SHA256 digest }
144 TSHA384Digest = packed array[0..47] of byte; {SHA384 digest }
145 TSHA512Digest = packed array[0..63] of byte; {SHA512 digest }
146 TSHA5_224Digest = packed array[0..27] of byte; {SHA512/224 digest}
147 TSHA5_256Digest = packed array[0..31] of byte; {SHA512/256 digest}
148 TWhirlDigest = packed array[0..63] of byte; {Whirlpool digest }
149 TSHA3_224Digest = packed array[0..27] of byte; {SHA3_224 digest }
150 TSHA3_256Digest = packed array[0..31] of byte; {SHA3_256 digest }
151 TSHA3_384Digest = packed array[0..47] of byte; {SHA3_384 digest }
152 TSHA3_512Digest = packed array[0..63] of byte; {SHA3_512 digest }
153 TBlake2S_224Digest = packed array[0..27] of byte; {Blake2S digest }
154 TBlake2S_256Digest = packed array[0..31] of byte; {Blake2S digest }
155 TBlake2B_384Digest = packed array[0..47] of byte; {Blake2B-384 digest}
156 TBlake2B_512Digest = packed array[0..63] of byte; {Blake2B-512 digest}
157
158
159 type
160 HashInitProc = procedure(var Context: THashContext);
161 {-initialize context}
162
163 HashUpdateXLProc = procedure(var Context: THashContext; Msg: pointer; Len: longint);
164 {-update context with Msg data}
165
166 HashFinalProc = procedure(var Context: THashContext; var Digest: THashDigest);
167 {-finalize calculation, clear context}
168
169 HashFinalBitProc = procedure(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
170 {-finalize calculation with bitlen bits from BData, clear context}
171
172 type
173 TOID_Vec = packed array[1..MaxOIDLen] of longint; {OID vector}
174 POID_Vec = ^TOID_Vec; {ptr to OID vector}
175
176 type
177 THashName = string[19]; {Hash algo name type }
178 PHashDesc = ^THashDesc; {Ptr to descriptor }
179 THashDesc = packed record
180 HSig : word; {Signature=C_HashSig }
181 HDSize : word; {sizeof(THashDesc) }
182 HDVersion : longint; {THashDesc Version }
183 HBlockLen : word; {Blocklength of hash, rate div 8 for SHA3}
184 HDigestlen: word; {Digestlength of hash}
185 HInit : HashInitProc; {Init procedure }
186 HFinal : HashFinalProc; {Final procedure }
187 HUpdateXL : HashUpdateXLProc; {Update procedure }
188 HAlgNum : longint; {Algo ID, longint avoids problems with enum size/DLL}
189 HName : THashName; {Name of hash algo }
190 HPtrOID : POID_Vec; {Pointer to OID vec }
191 HLenOID : word; {Length of OID vec }
192 HFill : word;
193 HFinalBit : HashFinalBitProc; {Bit-API Final proc }
194 HReserved : packed array[0..19] of byte;
195 end;
196
197
198 const
199 BitAPI_Mask: array[0..7] of byte = ($00,$80,$C0,$E0,$F0,$F8,$FC,$FE);
200 BitAPI_PBit: array[0..7] of byte = ($80,$40,$20,$10,$08,$04,$02,$01);
201
202 procedure RegisterHash(AlgId: THashAlgorithm; PHash: PHashDesc);
203 {-Register algorithm with AlgID and Hash descriptor PHash^}
204
205 function FindHash_by_ID(AlgoID: THashAlgorithm): PHashDesc;
206 {-Return PHashDesc of AlgoID, nil if not found/registered}
207
208 function FindHash_by_Name(AlgoName: THashName): PHashDesc;
209 {-Return PHashDesc of Algo with AlgoName, nil if not found/registered}
210
211 procedure HashFile({$ifdef CONST} const {$endif} fname: Str255; PHash: PHashDesc;
212 var Digest: THashDigest; var buf; bsize: word; var Err: word);
213 {-Calulate hash digest of file, buf: buffer with at least bsize bytes}
214
215 procedure HashUpdate(PHash: PHashDesc; var Context: THashContext; Msg: pointer; Len: word);
216 {-update context with Msg data}
217
218 procedure HashFullXL(PHash: PHashDesc; var Digest: THashDigest; Msg: pointer; Len: longint);
219 {-Calulate hash digest of Msg with init/update/final}
220
221 procedure HashFull(PHash: PHashDesc; var Digest: THashDigest; Msg: pointer; Len: word);
222 {-Calulate hash digest of Msg with init/update/final}
223
224 function HashSameDigest(PHash: PHashDesc; PD1, PD2: PHashDigest): boolean;
225 {-Return true if same digests, using HDigestlen of PHash}
226
227
228 implementation
229
230
231 var
232 PHashVec : array[THashAlgorithm] of PHashDesc;
233 {Hash descriptor pointers of all defined hash algorithms}
234
235 {---------------------------------------------------------------------------}
236 procedure RegisterHash(AlgId: THashAlgorithm; PHash: PHashDesc);
237 {-Register algorithm with AlgID and Hash descriptor PHash^}
238 begin
239 if (PHash<>nil) and
240 (PHash^.HAlgNum=longint(AlgId)) and
241 (PHash^.HSig=C_HashSig) and
242 (PHash^.HDVersion=C_HashVers) and
243 (PHash^.HDSize=sizeof(THashDesc)) then PHashVec[AlgId] := PHash;
244 end;
245
246
247 {---------------------------------------------------------------------------}
248 function FindHash_by_ID(AlgoID: THashAlgorithm): PHashDesc;
249 {-Return PHashDesc of AlgoID, nil if not found/registered}
250 var
251 p: PHashDesc;
252 A: longint;
253 begin
254 A := longint(AlgoID);
255 FindHash_by_ID := nil;
256 if (A>=ord(C_MinHash)) and (A<=ord(C_MaxHash)) then begin
257 p := PHashVec[AlgoID];
258 if (p<>nil) and (p^.HSig=C_HashSig) and (p^.HAlgNum=A) then FindHash_by_ID := p;
259 end;
260 end;
261
262
263 {---------------------------------------------------------------------------}
264 function FindHash_by_Name(AlgoName: THashName): PHashDesc;
265 {-Return PHashDesc of Algo with AlgoName, nil if not found/registered}
266 var
267 algo : THashAlgorithm;
268 phash: PHashDesc;
269
270 function StrUpcase(s: THashName): THashName;
271 {-Upcase for strings}
272 var
273 i: integer;
274 begin
275 for i:=1 to length(s) do s[i] := upcase(s[i]);
276 StrUpcase := s;
277 end;
278
279 begin
280 AlgoName := StrUpcase(Algoname);
281 {Transform RMD160 alias to standard name}
282 if AlgoName='RMD160' then AlgoName:='RIPEMD160';
283 FindHash_by_Name := nil;
284 for algo := C_MinHash to C_MaxHash do begin
285 phash := PHashVec[algo];
286 if (phash<>nil) and (AlgoName=StrUpcase(phash^.HName))
287 and (phash^.HSig=C_HashSig) and (phash^.HAlgNum=longint(algo))
288 then begin
289 FindHash_by_Name := phash;
290 exit;
291 end;
292 end;
293 end;
294
295
296 {---------------------------------------------------------------------------}
297 procedure HashUpdate(PHash: PHashDesc; var Context: THashContext; Msg: pointer; Len: word);
298 {-update context with Msg data}
299 begin
300 if PHash<>nil then with PHash^ do begin
301 if HSig=C_HashSig then HUpdateXL(Context, Msg, Len);
302 end;
303 end;
304
305
306 {---------------------------------------------------------------------------}
307 procedure HashFullXL(PHash: PHashDesc; var Digest: THashDigest; Msg: pointer; Len: longint);
308 {-Calulate hash digest of Msg with init/update/final}
309 var
310 Context: THashContext;
311 begin
312 if PHash<>nil then with PHash^ do begin
313 if HSig=C_HashSig then begin
314 HInit(Context);
315 HUpdateXL(Context, Msg, Len);
316 HFinal(Context, Digest);
317 end;
318 end;
319 end;
320
321
322 {---------------------------------------------------------------------------}
323 procedure HashFull(PHash: PHashDesc; var Digest: THashDigest; Msg: pointer; Len: word);
324 {-Calulate hash digest of Msg with init/update/final}
325 begin
326 {test PHash<>nil in HashFullXL}
327 HashFullXL(PHash, Digest, Msg, Len);
328 end;
329
330
331 {---------------------------------------------------------------------------}
332 function HashSameDigest(PHash: PHashDesc; PD1, PD2: PHashDigest): boolean;
333 {-Return true if same digests, using HDigestlen of PHash}
334 var
335 i: integer;
336 begin
337 HashSameDigest := false;
338 if PHash<>nil then with PHash^ do begin
339 if (HSig=C_HashSig) and (HDigestlen>0) then begin
340 for i:=0 to pred(HDigestlen) do begin
341 if PD1^[i]<>PD2^[i] then exit;
342 end;
343 HashSameDigest := true;
344 end;
345 end;
346 end;
347
348
349 {$i-} {Force I-}
350 {---------------------------------------------------------------------------}
351 procedure HashFile({$ifdef CONST} const {$endif} fname: Str255; PHash: PHashDesc;
352 var Digest: THashDigest; var buf; bsize: word; var Err: word);
353 {-Calulate hash digest of file, buf: buffer with at least bsize bytes}
354 var
355 {$ifdef VirtualPascal}
356 fms: word;
357 {$else}
358 fms: byte;
359 {$endif}
360 {$ifndef BIT16}
361 L: longint;
362 {$else}
363 L: word;
364 {$endif}
365 var
366 Context: THashContext;
367 f: file;
368 begin
369 if (PHash=nil) or (Phash^.HSig<>C_HashSig) then begin
370 Err := 204; {Invalid pointer}
371 exit;
372 end;
373 fms := FileMode;
374 {$ifdef VirtualPascal}
375 FileMode := $40; {open_access_ReadOnly or open_share_DenyNone;}
376 {$else}
377 FileMode := 0;
378 {$endif}
379 system.assign(f,{$ifdef D12Plus} string {$endif} (fname));
380 system.reset(f,1);
381 Err := IOResult;
382 FileMode := fms;
383 if Err<>0 then exit;
384 with PHash^ do begin
385 HInit(Context);
386 L := bsize;
387 while (Err=0) and (L=bsize) do begin
388 system.blockread(f,buf,bsize,L);
389 Err := IOResult;
390 HUpdateXL(Context, @buf, L);
391 end;
392 system.close(f);
393 if IOResult=0 then {};
394 HFinal(Context, Digest);
395 end;
396 end;
397
398
399 begin
400 {$ifdef HAS_ASSERT}
401 assert(sizeof(THashContext)=HASHCTXSIZE , '** Invalid sizeof(THashContext)');
402 {$else}
403 if sizeof(THashContext)<>HASHCTXSIZE then RunError(227);
404 {$endif}
405 {Paranoia: initialize all descriptor pointers to nil (should}
406 {be done by compiler/linker because array is in global data)}
407 fillchar(PHashVec,sizeof(PHashVec),0);
408 end.