Welcome to the new DelphiDabbler Code Library Documentation.

This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.

Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.

MD5 How-to: How To Get the MD5 Hash of Untyped Data

Applies to: ~>1.0

TPJMD5 provides an overload of both the TPJMD5.Calculate and TPJMD5.Process methods that can be used to calculate the MD5 hash of untyped data.

The methods both take a reference to the untyped data item as the first parameter and the length of the data as the second parameter.

For example, if you have a pointer P to some data that is 100 bytes long you would get its MD5 hash like this:

  D: TPJMD5Digest;
  P: Pointer;
  // set P to point to some 100 bytes of data
  // ...
  D := TPJMD5.Calculate(P^, 100);
  // ...
  // do something with D

This example is admittedly rather contrived, but it is not uncommon to have pointers to data you for which you want the MD5 hash. The main thing to note is that you must deference the pointer before call the method.

See the “How to get the MD5 hash of” topics for ordinal types, floats, arrays and records.

The main use for the Untyped overload of TPJMD5.Calculate and TPJMD5.Process is in getting the MD5 hash of ordinal values, floating point values, packed records and arrays of both these items. This is covered in more detail in other how-to pages, so a simple example will suffice here.

Suppose you have an array of Extended values. You can use TPJMD5.Process to get a MD5 hash of each item in the array, one element at a time, like this:

  AE: TArray<Extended>;
  E: Extended;
  MD5: TPJMD5;
  AE := TArray<Extended>.Create(0.42, 4.2, 42.0, 420.0, 4200.0);
  MD5 := TPJMD5.Create;
    for E in AE do
      MD5.Process(E, SizeOf(E));
    ShowMessage(MD5.Digest);  // uses of implicit cast of Digest to string

The reason why a TPJMD5Digest record can be passed to ShowMessage where a string argument is expected is explained here.

Here we create an arbitrary array of Extended values (using Delphi’s TArray<T> generic array type) and then iterate the array adding each Extended element in turn to the MD5 hash. Finally we access the hash via the TPJMD5.Digest property, using the untyped overload of TPJMD5.Process and display it in a message box. Notice how an array element is passed as the method’s first parameter and the size of the element is passed as the second. This adds all the bytes of the array element to the hash.

See Also