Page 1 of 1

SHA Hash from local File

Posted: Sun 14 Mar 2021 19:09
by JuergenD
Hi,
is it possible to get an SHA Hash String from a local file with SB ?
Like "idmd5.HashStreamAsHex(fs)" with indy.
Regards

Re: SHA Hash from local File

Posted: Mon 15 Mar 2021 12:16
by ViktorV
To solve the issue you can use the next code:

Code: Select all

const
  BUFFER_SIZE = 64 * 1024;

var
  Stream: TStream;
  Count: Int64;
  SHA: THash_SHA1;
  TmpBuf: TBytes;
  BufCount: integer;
  Buf: TBytes;
  Hash: string;
...

  SHA := THash_SHA1.Create;
  try
    Stream.Position := 0;
    Count := Stream.Size;

    SetLength(TmpBuf, BUFFER_SIZE);

    while Count > 0 do begin
      if Count > BUFFER_SIZE then
        BufCount := BUFFER_SIZE
      else
        BufCount := Count;

      Stream.ReadBuffer(TmpBuf[0], BufCount);
      SHA.TransformBlock(TmpBuf, 0, BufCount);
      Dec(Count, BufCount);
    end;
    SHA.TransformFinalBlock(nil, 0, 0);
    Buf := SHA.Hash;
    Hash := BytesToHexStr(Buf);
  finally
    SHA.Free;
  end;
Note that to run this code, you should add the ScUtils, ScHash units to the USES clause of your module.

Re: SHA Hash from local File

Posted: Mon 15 Mar 2021 15:44
by JuergenD
Great, many thanks.
And it is realy fast!

Re: SHA Hash from local File

Posted: Tue 16 Mar 2021 05:42
by ViktorV
Thank you for interest to our product.
Feel free to contact us if you have any further questions about our products.