Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Compute a SHA-256 hash and an HMAC

A hash turns any amount of data into a short fixed-size value: the same input always gives the same digest, and a change anywhere in the input changes it. An HMAC is a hash keyed with a secret, so only someone who holds the key can compute it - it proves that the data came from such a party and was not changed on the way.

Which hash

Use SHA-256 unless a protocol prescribes something else; SHA-384, SHA-512, SHA-3 and BLAKE2b are there too (haSHA384, haSHA512, haSHA3_256, haBlake2b512, each available once its unit is in a uses clause). MD5 and SHA-1 are only for reading old data: neither is safe where an attacker chooses the input.

The units

A hash algorithm is linked into the program by using its unit; the helper routines find it by its tHashAlgorithm value.

uses
  System.SysUtils,
  stDERUtils,     // OctetString, OSToHex, UnicodeToUtf8
  stSecUtils,     // DigestString, DigestFile, HMACString, EqualMemConstantTime
  stSHA256;       // links SHA-224/256 in: a hash is available once its unit is used
If the unit of an algorithm is not linked, DigestString, DigestFile and
HMACString return an EMPTY result rather than raise - a missing unit shows
up as an empty digest, not as an error.

Hash a string or a file

function Sha256Hex(const aText: string): string;
begin
  { Hash the UTF-8 octets of the text - a hash is over bytes, and UTF-8 is
    what another program will most likely have hashed. }
  Result := OSToHex(DigestString(haSHA256, UnicodeToUtf8(aText)), True);
end;

function Sha256FileHex(const aFileName: string): string;
begin
  { The file is read in blocks; its size does not matter. }
  Result := OSToHex(DigestFile(haSHA256, aFileName), True);
end;

Sha256Hex('abc') returns ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad, the value FIPS 180-4 gives for that input. DigestStream does the same for any TStream, from its current position to its end.

Compute and check an HMAC

function HmacSha256Hex(const aKey, aMessage: OctetString): string;
begin
  { 32 = the full SHA-256 output; a shorter length truncates the MAC. }
  Result := OSToHex(HMACString(haSHA256, aKey, 32, aMessage), True);
end;

function HmacSha256Verify(const aKey, aMessage, aExpectedMac: OctetString): Boolean;
var
  lMac, lExpected: TBytes;
begin
  lMac := OSToBytes(HMACString(haSHA256, aKey, 32, aMessage));
  lExpected := OSToBytes(aExpectedMac);
  { Compare in constant time: an ordinary comparison stops at the first
    differing byte, and the time it takes tells an attacker how much of a
    forged MAC was right. }
  Result := (Length(lExpected) = Length(lMac)) and
            EqualMemConstantTime(lMac[0], lExpected[0], Length(lMac));
end;
Check a received MAC with EqualMemConstantTime, never with = or
CompareMem: those return as soon as one byte differs, and how long they
take tells an attacker how many bytes of a forged MAC were right.

The key should be random and at least as long as the hash output (32 octets for SHA-256); see Generate random bytes and keys. For a key derived from a password, see Store a password safely.

On a form

The same algorithms are available as a component: drop a TstHash on the form, choose its algorithm in the Object Inspector, and call its methods in place of the routines above.

Reference

TstHash · stSecUtils · stSHA256

Related tasks