Calculate MD5 Hashing for a File or String Using Delphi

Young Asian businesswoman working on laptop in board room
Steve Debenport/E+/Getty Images

The MD5 Message-Digest Algorithm is a cryptographic hash function. MD5 is commonly used to check the integrity of files, like to make sure that a file has been unaltered.

One example of this is when downloading a program online. If the software distributor gives out the MD5 hash of the file, you can produce the hash using Delphi and then compare the two values to make sure they're the same. If they're different, it means the file you downloaded is not the one you requested from the website, and therefore may be malicious.

An MD5 hash value is 128-bits long but is typically read in its 32 digit hexadecimal value.

Finding the MD5 Hash Using Delphi

Using Delphi, you can easily create a function to calculate the MD5 hash for any given file. All you need is included in the two units IdHashMessageDigest and idHash, both of which are a part of Indy.

Here's the source code:

 uses IdHashMessageDigest, idHash;
//returns MD5 has for a file
function MD5(const fileName : string) : string;
var
  idmd5 : TIdHashMessageDigest5;
  fs : TFileStream;
  hash : T4x4LongWordRecord;
begin
  idmd5 := TIdHashMessageDigest5.Create;
  fs := TFileStream.Create(fileName, fmOpenRead OR fmShareDenyWrite) ;
  try
    result := idmd5.AsHex(idmd5.HashValue(fs)) ;
  finally
    fs.Free;
    idmd5.Free;
  end;
end;

Other Ways to Generate the MD5 Checksum

Apart from using Delphi are other ways you can find the MD5 checksum of a file.

One method is to use Microsoft File Checksum Integrity Verifier. It's a free program that can be used only on the Windows OS.

MD5 Hash Generator is a website that does something similar, but instead of producing the MD5 checksum of a file, it does so from any string of letters, symbols, or numbers that you put in the input box.

Format
mla apa chicago
Your Citation
Gajic, Zarko. "Calculate MD5 Hashing for a File or String Using Delphi." ThoughtCo, May. 14, 2018, thoughtco.com/md5-hashing-in-delphi-1058202. Gajic, Zarko. (2018, May 14). Calculate MD5 Hashing for a File or String Using Delphi. Retrieved from https://www.thoughtco.com/md5-hashing-in-delphi-1058202 Gajic, Zarko. "Calculate MD5 Hashing for a File or String Using Delphi." ThoughtCo. https://www.thoughtco.com/md5-hashing-in-delphi-1058202 (accessed May 27, 2018).