hash.pas 16 KB

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