Delphi: How to calculate the SHA hash of a large file

前端 未结 5 709
囚心锁ツ
囚心锁ツ 2021-02-08 05:18

Hi I need to generate a SHA over a 5 Gig file

Do you know of a non string based Delphi library that can do this ?

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 05:43

    @Davy Landman, thank you, your answer really helped me out. This is the code I ended up using:

    function HashFileSHA256(const fileName: String): String;
    var
      sha256: TDCP_sha256;
      buffer: array[0..1024*1024] of byte;
      i, bytesRead: Integer;
      streamIn: TFileStream;
      hashBuf: array[0..31] of byte;
    begin
      // Initialization
      Result := '';
      streamIn := TFileStream.Create(fileName, fmOpenRead);
      sha256 := TDCP_sha256.Create(nil);
      for i:=0 to Sizeof(buffer) do
        buffer[i] := 0;
      for i:=0 to Sizeof(hashBuf) do
        hashBuf[i] := 0;
      bytesRead := -1;
    
      // Compute
      try
        sha256.Init;
        while bytesRead <> 0 do
        begin
          bytesRead := streamIn.Read(buffer[0], Sizeof(buffer));
          sha256.Update(buffer[0], bytesRead);
        end;
        sha256.Final(hashBuf);
        for I := 0 to 31 do
          Result := Result + IntToHex(hashBuf[i], 2);
      finally
        streamIn.Free;
        sha256.Free;
      end;
    
      Result := LowerCase(Result);
    end;
    

    P.S.: I am a total beginner with Pascal, so this code most likely sucks. But I tested it on the MSYS2 installer and was able to verify the hash, so that's nice.

提交回复
热议问题