Wednesday, April 15, 2015

System.Hash in Delphi XE8

Delphi XE8 introduced new unit System.Hash.

There are few popular hashes implemented:

  • MD5: THashMD5
  • SHA1: THashSHA1
  • Bob Jenkins Hash: THashBobJenkins
Hashes implemented as records.

Using is quite obvious:
  • Create hash (calls Reset internally)
  • Update hash, there are overloaded Update procedures to update from untyped buffer, from TBytes and from string.
  • Finally call HashAsBytes to get digest as TBytes or call HashAsString to get digest as string.
For example:

procedure test;
var
  Hash: THashMD5;
  digestString: string;
begin
  Hash := THashMD5.Create;
  Hash.Update('test');
  digestString := Hash.HashAsString;
end;

Or even simpler, class functions GetHashBytes and GetHashString can be used, like:

digestString := THashMD5.GetHashString('test'); // '098f6bcd4621d373cade4e832627b4f6'

And 2 more HMAC related functions in THashMD5 and THashSHA1:

  class function GetHMAC(const AData, AKey: string): string;
  class function GetHMACAsBytes(const AData, AKey: string): TBytes;


THash record hash following class functions:

DigestAsInteger to represent array of 4 bytes as Integer (no endianness conversion).
DigestAsString to represent TBytes as hex string in lower case. (IMO that could better be helper for TBytes in SysUtils).
DigestAsStringGUID to represent array of 16 bytes as GUID (big-endian).
GetRandomString produce random string of specified length using following chars

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-/*_

ToBigEndian which swaps bytes of Cardinal argument.

No comments:

Post a Comment