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: Understand the Calculate and Process methods

Applies to: ~>1.0

TPJMD5.Calculate and TPJMD5.Process are methods of TPJMD5 within similar purposes but some significant differences.

Both methods are used in creating MD5 hashes. Both have numerous overloaded versions.

Process

TPJMD5.Process is used to add one or more items of data to a TPJMD5 instance. When all the data has been added the resulting hash (or digest) is read using the instance’s TPJMD5.Digest property.

Here’s an example where we add data from a byte array and an ANSI string to the same MD5 hash, using the AnsiString and one of the TBytes overloads of TPJMD5.Process:

function Foo(const S: AnsiString; const B: TBytes): TPJMD5Digest;
var
  MD5: TPJMD5;
begin
  MD5 := TPJMD5.Create;
  try
    MD5.Process(S);
    MD5.Process(B);
    Result := MD5.Digest;
  finally
    MD5.Free;
  end;
end;

You can mix and match any data in a single hash. However it is much more common to get the hash of just a single data item, for example of the contents of a TBytes array, like this:

function Bar(const B: TBytes): TPJMD5Digest;
var
  MD5: TPJMD5;
begin
  MD5 := TPJMD5.Create;
  try
    MD5.Process(B);
    Result := MD5.Digest;
  finally
    MD5.Free;
  end;
end;

Because this is so common an idiom a short-cut would be great. And that’s where TPJMD5.Calculate comes in.

Calculate

TPJMD5.Calculate is set of overloaded class function gets the MD5 hash of a single data item without the need to construct a TPJMD5 instance. For every overload of TPJMD5.Process there is a matching TPJMD5.Calculate overload.

Effectively all call to TPJMD5.Calculate is equivalent to this code:

function TPJMD5.Calculate(param-list): TPJMD5Digest; overload;
var
  MD5: TPJMD5;
begin
  MD5 := TPJMD5.Create;
  try
    MD5.Process(param-list);
    Result := MD5.Digest;
  finally
    MD5.Free;
  end;
end;

For example, we can now re-implement the Bar function from above using a TBytes overload of TPJMD5.Calculate like this:

function Bar(const B: TBytes): TPJMD5Digest;
begin
  Result := TPJMD5.Calculate(B);
end;

Of course you wouldn’t bother implementing Bar now, you would just make the direct call to TPJMD5.Calculate.

See Also