Search code examples
delphihashsha-3

How to hash a string with SHA-3/256 with Delphi XE8?


I'm trying to hash a string using the CRC/Hash library from Wolfgang Ehrardt and I'm trying to use the SHA3/256 algorithm. I wrote this procedure:

procedure TForm1.Button1Click(Sender: TObject);
var
  Context : THashContext;
  Digest: TSHA3_256Digest;
  buf:   TBytes;
  s: string;
begin
  buf := TEncoding.UTF8.GetBytes('0123456789012345');
  SHA3_256Full(Digest, buf, SizeOF(buf));
  s:=HexStr(@Digest, SizeOf(Digest)); //HexStr is in mem_utils unit from the same CRC/Hash library

  memo1.lines.clear;
  memo1.Lines.add(s);
end;

The resulting hash is b64f67d4a6fe871afc5c42e3128b5e3b6943c475bab1a138667c0213e1f9a6bb but it differs from the result obtained through the SHA-3/256 tool at http://emn178.github.io/online-tools/sha3_256.html, where the same string gives 4e058e17199441d69589d3c775face0c4949af7f4f011317efce2fc22606c428.

On the other side, if I try to hash a blank string, the result is a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a which is correct.

So the question is: am I making any mistake in my code?


Solution

  • Because buf is a dynamic array variable, implemented as a pointer, SizeOf(buf) is the size of a pointer. Either 4 or 8 depending on your target. I don't think that's what you intend at all. You intend to pass the length of the byte array. So, replace

    SizeOf(buf)
    

    with

    Length(buf)
    

    This program

    {$APPTYPE CONSOLE}
    
    uses
      SysUtils,
      mem_util, hash, sha3_256;
    
    var
      Digest: TSHA3_256Digest;
      buf: TBytes;
    
    begin
      buf := TEncoding.UTF8.GetBytes('0123456789012345');
      SHA3_256Full(Digest, buf, Length(buf));
      Writeln(HexStr(@Digest, SizeOf(Digest)));
    end.
    

    outputs

    4e058e17199441d69589d3c775face0c4949af7f4f011317efce2fc22606c428