4

我正在尝试使用 Wolfgang Ehrardt 的 CRC/Hash 库对字符串进行哈希处理,并且正在尝试使用 SHA3/256 算法。我写了这个程序:

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 .

另一方面,如果我尝试散列一个空白字符串,结果是a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a是正确的。

所以问题是:我的代码是否有任何错误?

4

1 回答 1

4

因为buf是动态数组变量,实现为指针,SizeOf(buf)是指针的大小。4个或8个,具体取决于您的目标。我认为这根本不是你想要的。您打算传递字节数组的长度。所以,更换

SizeOf(buf)

Length(buf)

这个节目

{$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.

输出

4e058e17199441d69589d3c775face0c4949af7f4f011317efce2fc22606c428
于 2016-02-29T15:39:46.393 回答