1

I'm trying to generate a hash from a PDF. This hash should be SHA256 and Base64. I'm using a simple PDF with one line with the content: Hello World.

With the C# code below I've got the result: Gv5AR2YOxUVOjx+QFakM56Wj7CSqeZWiaVqczra/iBk=

string digest;
using (SHA256Managed sha = new SHA256Managed())
{
    byte[] hash = sha.ComputeHash(pdf);
    digest = Convert.ToBase64String(hash);
}

Then, using Delphi, with the code below, I've got this: wPUoG1guk2hQ5TxS5lUmaMLk83E=

// uses IdCoderMIME, IdHashSHA, IdGlobal;

var
  oHash: TIdHashSHA1;
  oFileStream: TFileStream;
begin
  oHash := TIdHashSHA1.Create;
  oFileStream := TFileStream.Create(edtPDFPath.Text, fmOpenRead);
  try
    result := TIdEncoderMIME.EncodeBytes(oHash.HashStream(oFileStream, 0, oFileStream.Size));
  finally
    Freeandnil(oFileStream);
    oHash.Free
  end;

I need to hash this file with Delphi but I don't know if my result is right or not.

Someone knows another way to get as a result a SHA256 Base64 hash?

JPT
  • 13
  • 2
  • 9
    SHA1 is not SHA256. `TIdHashSHA1` implements SHA1. `SHA256Managed` implements SHA256. They are not the same. Note that SHA1 has been deprecated for a decade and a half. – J... Apr 15 '21 at 22:42
  • 1
    Related : [SHA 256 With Indy](https://stackoverflow.com/q/43173249/327083) – J... Apr 15 '21 at 22:44

1 Answers1

1

You can get same result as C# with following code

// uses System.Hash, System.NetEncoding;
Result := TNetEncoding.Base64.EncodeBytesToString(THashSHA2.GetHashBytes(oFileStream, THashSHA2.TSHA2Version.SHA256));
EugeneK
  • 2,164
  • 1
  • 16
  • 21
  • Thank you @Eugenek . Now I am trying to decrypt the hashed String and save it to a PDF file again, but I can't find a way to do this. I've tried something like bellow: `var stream: TBytesStream; begin stream := TBytesStream.Create(TNetEncoding.Base64.DecodeStringToBytes(base64HashString)); try stream.SaveToFile(Filename); finally stream.Free; end; ` But the generated file is corrupted, with invalid characters. – JPT May 09 '21 at 21:48
  • I'm not sure what are you trying to achieve, you cannot recover PDF file from its hash, it is one way operation. – EugeneK May 10 '21 at 18:54