Hash a file with MD5

This tutorial continues from Encrypt a file.

Setup

Put another button on the main form and caption it "Hash".
Add a THash component to the form and connect it up to the existing TCryptographicLibrary component.
Pull down the choices for the Hash property of the Hash component. List Hash algorithms include MD5 and a large number from the SHA family. Select MD5.

MD5 is weak hash and shouldn't be used for protecting high value assets. But you might have good reasons to use it for interoperability because it is widely used, for example in the Facebook API.
 

Operation

Now implement the event handler for the Hash button like so …

procedure TmfmWestwood3DES_Tut.btnHashClick(Sender: TObject);
var
  sSourceFN: string;
begin
if not dlgOpenPlaintext.Execute then exit;
try
  Put( '', []);  // Empty line.
  sSourceFN  := dlgOpenPlaintext.FileName;
  Put( 'Now computing MD5 hash on file "%s".', [sSourceFN]);
  Hash1.HashFile( sSourceFN);
  // The binary value of the hash can now be found in the stream Hash1.HashOutputValue
  Put( 'The base64 representation of the hash output is %s.',
    [Stream_to_Base64( Hash1.HashOutputValue)])
except on E: Exception do
    begin
    Put( '%s: %s', [E.ClassName, E.Message]);
    end
  end;
end;

You will need to include the unit uTPLb_StreamUtils to gain access to the Stream_to_Base64 function.

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享